简体   繁体   中英

How to sort by two fields in Java and specify sort direction?

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.

As simple as adding a reversed ...

list.sort(Comparator.comparing(ClassA::getVar1)
                   .thenComparing(Comparator.comparing(ClassA::getVar2).reversed()));

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

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM