List>之按照某个字段排序

时间:2022-05-26 15:01:15
//这是你自己用来接受查询出来的数据的集合。
 List<Map<String,Object>> listMap1 = new LinkedList<Map<String,Object>>();
//这是我集合中的数据(泥萌可以拿去当静态数据用)
[{"count":205,"ip":"10.0.30.96"},{"count":79,"ip":"10.0.30.76"},{"count":39,"ip":"10.0.30.75"},{"count":38,"ip":"10.0.30.83"},{"count":37,"ip":"10.0.30.78"},{"count":33,"ip":"10.0.30.84"},{"count":20,"ip":"10.0.30.53"},{"count":17,"ip":"10.0.10.112"},{"count":12,"ip":"10.0.30.79"},{"count":11,"ip":"10.0.30.81"},{"count":6057,"ip":"192.168.1.195"},{"count":2077,"ip":"192.168.1.97"},{"count":943,"ip":"192.168.1.70"},{"count":813,"ip":"192.168.1.100"},{"count":727,"ip":"192.168.1.79"},{"count":647,"ip":"192.168.1.87"},{"count":629,"ip":"192.168.1.21"},{"count":182,"ip":"192.168.1.155"},{"count":168,"ip":"192.168.1.95"},{"count":160,"ip":"192.168.1.93"}]     

// 数据的话 可以自己去手动添加静态的ang~

//接下来到关键时刻了~      要注意line.3位置的count   是对应你自己数据集合中的count

Collections.sort(listMap1, new Comparator<Map<String,Object>>(){  
            public int compare(Map<String,Object> o1,Map<String,Object> o2){  
            return  (Long)o1.get("count")<(Long)o2.get("count")?1:( (Long)o1.get("count")==(Long)o2.get("count")?0:-1);
            }  
        });  
        System.out.println("排序:"+listMap1);
//然后就是叼叼哒的排序    long 是指你自己的count的类型,排序的话只是更改一下大于小于符号即可~
     return  (Long)o1.get("count")>(Long)o2.get("count")?1:( (Long)o1.get("count")==(Long)o2.get("count")?0:-1);//这是从小到大
     return  (Long)o1.get("count")<(Long)o2.get("count")?1:( (Long)o1.get("count")==(Long)o2.get("count")?0:-1);//这是从大到小

//然后......   就没有然后了

PS:以上内容转载自:  http://www.cnblogs.com/xiaolonger/p/4428537.html