当前位置: 移动技术网 > IT编程>开发语言>Java > JAVA对list集合进行排序Collections.sort()

JAVA对list集合进行排序Collections.sort()

2019年07月22日  | 移动技术网IT编程  | 我要评论
对一个集合中的对象进行排序,根据对象的某个指标的大小进行升序或降序排序。代码如下: 进行降序排列 进行降序排列 collections.sort

对一个集合中的对象进行排序,根据对象的某个指标的大小进行升序或降序排序。代码如下:

进行降序排列

 进行降序排列
    collections.sort(list, new comparator<resulttypedesc>() {
      public int compare(resulttypedesc o1, resulttypedesc o2) {
        return o2.getratio().compareto(o1.getratio());
      }
    });

进行升序排列

collections.sort(list, new comparator<resulttypedesc>() {
public int compare(resulttypedesc o1, resulttypedesc o2) {
return o1.getratio().compareto(o2.getratio());
   }
});

经过测试发现,只需要把两个对象的位置调换一下即可升序或降序。

如果指标相同,根据多个指标进行排序,需创建一个比较器:

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

对list集合进行逆输出:

collections.reverse(list);

resulttypedesc这个为所需的实体类对象,具体使用结合自己代码情况即可。

此方法有可能报空指针,自己结合情况,自行解决,判断是否为null。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网