根据对象的某个字段对List<Object>排序

首先说下需求,在开发中会遇到对List<Object>进行排序,这个也可以在数据库里面查询排序出来,但是有的时候会在查出来之后做一些逻辑处理然后排序,所有就要用到对象排序。

  • 首先创建一个类实现Comparator<T> 接口,并重写int compare(T t1, T t2)接口
  1. [java]  view plain  copy
     print ? 在CODE上查看代码片 派生到我的代码片
    1. import java.util.Comparator;  
    2.   
    3. /** 
    4.  * Created by wanghaiyang on 2016/4/11. 
    5.  */  
    6. public class ComparatorUtil implements Comparator<ApiCounterResponse> {  
    7.     //倒序排列即从大到小,若需要从小到大修改返回值1 和 -1   
    8.     public int compare(ApiCounterResponse o1, ApiCounterResponse o2) {  
    9.         double tempResult1 = o1.getTempResult();  
    10.         double tempResult2 = o2.getTempResult();  
    11.         if (tempResult1 > tempResult2) {  
    12.             return -1;  
    13.         } else if (tempResult1 < tempResult2) {  
    14.             return 1;  
    15.         } else {  
    16.             return 0;  
    17.         }  
    18.     }  
    19. }  

  • new一个实现类对象,传地参数需要排序的List对象和Comparator的实现类
  1. [java]  view plain  copy
     print ? 在CODE上查看代码片 派生到我的代码片
    1. public static void main(String[] args) {  
    2.        List<ApiCounterResponse> listCounter = new ArrayList<ApiCounterResponse>();  
    3.   
    4.        for (int i = 0; i < 10; i ++) {  
    5.            ApiCounterResponse api = new ApiCounterResponse();  
    6.            api.setMethodId(1L + i);  
    7.            api.setTempResult(2.34 + i);  
    8.            listCounter.add(api);  
    9.            System.out.println(listCounter.get(i).getMethodId());  
    10.        }  
    11.   
    12.        //在这里进行排序(具体实现看源代码)     
    13.        Comparator comp = new ComparatorUtil();  
    14.        Collections.sort(listCounter, comp);  
    15.   
    16.        for (int i = 0; i < listCounter.size(); i++) {  
    17.            System.out.println(listCounter.get(i).getMethodId());  
    18.        }  
    19.    }  
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值