How to Sort hashSet by two conditions?

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"}]

Last updated:5/30/2015 7:47:29 AM

1 Answers

Anonymous User
Anonymous User

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);
});

Answer