HOW TO SORT HASHSET BY TWO CONDITIONS?

Kamlakar Singh

Total Post:194

Points:1396
Posted by  Kamlakar Singh
 1113  View(s)
Ratings:
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"}]

  1. Jessica James

    Post:16

    Points:114
    Re: How to Sort hashSet by two conditions?

    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 Apr-09-2018 11:38:18 PM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!