Home > Java > javaTutorial > body text

JAVA sorts list collectionCollections.sort()

高洛峰
Release: 2017-01-23 16:49:04
Original
1975 people have browsed it

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());
     }
   });
Copy after login

Arrange in ascending order

Collections.sort(list, new Comparator<ResultTypeDesc>() {
public int compare(ResultTypeDesc o1, ResultTypeDesc o2) {
return o1.getRatio().compareTo(o2.getRatio());
   }
});
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template