Home > DeveloperSection > Forums > How to Sort hashSet by two conditions?
Kamlakar Singh
Kamlakar Singh

Total Post:194

Points:1396
Posted on    May-30-2015 7:44 AM

 Java Hashtable 
Ratings:


 1 Reply(s)
 525  View(s)
Rate this:

I’m want to sorting a category bu name and place categories with ids: -1, 0 in begin

public class Category {

    Long id;

    String name;

 

    public Category(Long id, String name) {

        this.id=id;

        this.name=name;

    }   

}

 

Set<Categories> categories = new HashSet<>;

categories.add(new Category(2,"Kamlakar"))

categories.add(new Category(-1,"Pawan"))

categories.add(new Category(3,"Haider"))

categories.add(new Category(1,"Manoj"))

categories.add(new Category(0,"All"))

 

how to get such list

[{-1," Pawan "}, {0,"All"}, {3," Haider "}, {1," Kamlakar "}, {2,"Historical"}]



Jessica James
Jessica James

Total Post:16

Points:114
Posted on    May-30-2015 7:47 AM


Try this code:


Collections.sort(categories, (a, b) -> {

    if (a.id != b.id) {

        if (a.id == -1) {

            return -1;

        }

        if (b.id == -1) {

            return 1;

        }

        if (a.id == 0) {

            return -1;

        }

        if (b.id == 0) {

            return 1;

        }

    }

    return a.name.compareTo(b.name);

});


Modified On Mar-18-2016 11:20:35 PM

Don't want to miss updates? Please click the below button!

Follow MindStick