JAVA sorts the list set Collections.sort of
- 2020-05-26 08:36:10
- OfStack
Sort the objects in a collection in ascending or descending order according to the size of a certain index of the object. The code is as follows:
So let's do it in descending order
So let's do it in descending order
Collections.sort(list, new Comparator<ResultTypeDesc>() {
public int compare(ResultTypeDesc o1, ResultTypeDesc o2) {
return o2.getRatio().compareTo(o1.getRatio());
}
});
I'm going to do it in ascending order
Collections.sort(list, new Comparator<ResultTypeDesc>() {
public int compare(ResultTypeDesc o1, ResultTypeDesc o2) {
return o1.getRatio().compareTo(o2.getRatio());
}
});
After testing, it is found that only need to change the position of the two objects 1 can be ascending or descending.
If the indexes are the same, sort them according to multiple indexes, and create a comparator:
import java.util.*;
public class ComparatorResultType implements Comparator{
public int compare(Object arg0, Object arg1) {
ResultTypeDesc desc0=(ResultTypeDesc)arg0;
ResultTypeDesc desc1=(ResultTypeDesc)arg1;
// First compare the main index, if the main index is the same, then compare the secondary index
int flag=desc0.getXXX().compareTo(desc1.getXXX());
if(flag==0){
return desc0.getXXX2().compareTo(desc1.getXXX2());
}else{
return flag;
}
}
}
// Code in the test class:
ComparatorResultType comparator=new ComparatorResultType();
Collections.sort(list, comparator);
Inverse output of list set:
Collections.reverse(list);
ResultTypeDesc is the required entity class object, which can be used in combination with its own code.
It is possible for this method to declare a null pointer, solve it by itself in combination with the situation, and judge whether it is NULL.