1

I have a list of object i want to sort it using two properties. i have searched on internet and i find this solution in java 8.

class ClassA {
    String var2; 
    String var1;
    // getters and setters
}

List<classA> list;
list.sort(Comparator.comparing(ClassA::getVar1).thenComparing(ClassA::getVar2));

this absolutely works and perfectly, but what I want is to use descending sorting on var2 and ascending sorting on var1.

2
  • 2
    You have ClassA::var2 twice in your example. Commented Aug 16, 2018 at 15:10
  • I've edited to what makes me think is correct... Commented Aug 16, 2018 at 15:14

3 Answers 3

6

As simple as adding a reversed...

list.sort(Comparator.comparing(ClassA::getVar1)
                   .thenComparing(Comparator.comparing(ClassA::getVar2).reversed()));
Sign up to request clarification or add additional context in comments.

3 Comments

i try that but the problem it reversed all sorts on var1 and var2
@kimo815 care to provide a minimal example of what exactly you mean?
@Eugene I suspect OP probably mismatched your parentheses
0

You need to implement the Comparable interface.

Somtehing like this :

class A implements Comparable{
    @Override public int compareTo(A anObjectA) {
        if (this == anObjectA) return 0;
        int ret = var2.compareTo(anObjectA.var2);
        if(ret == 0)
        ...
    }
}

Comments

0

You could make use of the java comparable interface. Something like this could work:

import java.util.*;  
class classAComparator implements Comparator{  
public int compareTo(classA a,classA b){ 
     int res = a.var2.compareTo(b.var2);
     if(res == 0) { //var2 was the same
          //compare using var1 in descending order
     }
     return res;
 }             

You would use this by running list.sort(new classAComparator())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.