Home >Java >javaTutorial >JAVA sorts list collectionCollections.sort()
Sort the objects in a collection in ascending or descending order according to the size of a certain indicator of the object. The code is as follows:
Arrange in descending order
进行降序排列 Collections.sort(list, new Comparator<ResultTypeDesc>() { public int compare(ResultTypeDesc o1, ResultTypeDesc o2) { return o2.getRatio().compareTo(o1.getRatio()); } });
Arrange 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 was found that only two The position of the objects can be changed in ascending or descending order.
If the indicators are the same, to sort based on multiple indicators, you need to 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; //首先比较主指标,如果主指标相同,则比较次指标 int flag=desc0.getXXX().compareTo(desc1.getXXX()); if(flag==0){ return desc0.getXXX2().compareTo(desc1.getXXX2()); }else{ return flag; } } } //测试类中代码: ComparatorResultType comparator=new ComparatorResultType(); Collections.sort(list, comparator);
Inverse output of the list collection:
Collections .reverse(list);
ResultTypeDesc is the required entity class object. The specific use can be combined with your own code.
This method may report a null pointer. You can solve it yourself based on the situation and determine whether it is NULL.
For more JAVA sorting list collections Collections.sort() related articles, please pay attention to the PHP Chinese website!