1

I have a Member class like this :

public class Member {
    private int value1;
    private boolean value2;
}

And an ArrayList<Member> containing this data :

value1 - value2

  • 1 - false
  • 2 - false
  • 3 - true
  • 4 - false
  • 5 - true

Now I want this data sorted this way :

  • The members with value2 as true must be returned first, then the other ones after
  • In each sublist, members will be returned from the highest to the lowest value1

So in the end, the list should contain data in this order : 5, 3, 4, 2, 1.

I know that I can use Collections.sort() to sort data by value1 :

Collections.sort(memberList, new Comparator<Member>(){
    public int compare(Member m1, Member m2){
        return m1.getValue1() - m2.getValue1();
    }
});

But is there a way to sort data by both criterias in the same compare method?

Thanks for your help.

Rob
  • 4,123
  • 3
  • 33
  • 53

2 Answers2

2

You can compare by value2 first, and then in the case of a tie compare by value1:

Collections.sort(memberList, new Comparator<Member>(){
    public int compare(Member m1, Member m2){
        int comp = Boolean.compare(m1.getValue2(), m2.getValue2());

        if (comp == 0) {
            // case where 'value2' is the same for both inputs
            // in this case use 'value1' to compare
            comp = m1.getValue1() - m2.getValue1();
        }
        return comp;
    }
});
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2
Collections.sort(memberList, new Comparator<Member>(){
    public int compare(Member m1, Member m2){
        int res = Boolean.compare(m2.getValue2(), m1.getValue2());
        if(res == 0) res = Integer.compare(m2.getValue1(), m1.getValue1());
        return res;
    }
});

This can be done much more simply in Java-8:

Collections.sort(memberList, 
       Comparator.comparing(Member::getValue2).thenComparing(Member::getValue1).reversed());
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334