ArrayList 根据某一属性排序

这里要使用java.util.Comparator 接口和集合工具类Collections的sort()方法


/**
     * 获取商家下设备终端数据统计
     * @param businessUserId
     * @return
     */
    public String getDeviceVendorStat(String businessUserId,Long createTime){

      //定义设备内部类  

    class Device {

            //设备类型

            private String deviceName;
            //设备数量
            private long count;

            public String getDeviceName() {
                return deviceName;
            }
            public void setDeviceName(String deviceName) {
                this.deviceName = deviceName;
            }
            public long getCount() {
                return count;
            }
            public void setCount(long count) {
                this.count = count;
            }
        }
        
        //根据业务需要编写比较类   这里根据设备类型的(count)个数进行比较
        Comparator<Device> comparator = new Comparator<Device>(){
            @Override   
            public int compare(Device o1, Device o2) {
                if(o1.getCount()!=o2.getCount()){
                 return -(int) (o1.getCount()-o2.getCount());
                }
                else{
                    return -o1.getDeviceName().compareTo(o1.getDeviceName());
                }
               }
        };

        //组装需要进行排序的ArrayList
        List deviceVendoList=new ArrayList();
        try {
            List<?> deviceVendor=marketCounterDAO.getDeviceVendorStat(businessUserId,createTime);
            if(deviceVendor!=null&&deviceVendor.size()>0){
                String deviceNames[] = {"小米","华为","苹果","htc","三星","其他"};
            Object[] obj=(Object[])deviceVendor.get(0);
            for (int i = 0; i < obj.length; i++) {
                Device device = new Device();
                device.setDeviceName(deviceNames[i]);
                device.setCount(Long.valueOf(obj[i].toString()));
                deviceVendoList.add(device);
            }
            }

            //进行排序
            Collections.sort(deviceVendoList,comparator);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return JacksonUtil.buildNonNullBinder().toJson(deviceVendoList);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值