根据map集合的value进行排序

本项目用到排序

1.map集合类型 Map

//自定义比较器
            Comparator<Map.Entry<String, Double>> valueComparator = new Comparator<Map.Entry<String, Double>>() {
                @Override
                public int compare(Entry<String, Double> o1, Entry<String, Double> o2) {
                    return o1.getValue().compareTo(o2.getValue());
                }
            };
            // map转换成list进行排序
            List<Map.Entry<String, Double>> list = new ArrayList<Map.Entry<String, Double>>(avgMap.entrySet());
            // 排序
            Collections.sort(list, valueComparator);

自定义demo

    @Test
    public void demo2() {
        Map<String, Double> map = new TreeMap<String, Double>();
        map.put("acb1", 5.1);
        map.put("bac1", 3.1);
        map.put("bca1", 2.9);
        map.put("cab1", 80.1);
        map.put("cba1", 1.1);
        map.put("abc1", 10.1);
        map.put("abc2", 12.1);
        Comparator<Map.Entry<String, Double>> valueComparator = new Comparator<Map.Entry<String, Double>>() {
            @Override
            public int compare(Entry<String, Double> o1, Entry<String, Double> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        };
        // map转换成list进行排序
        List<Map.Entry<String, Double>> list = new ArrayList<Map.Entry<String, Double>>(map.entrySet());
        // 排序
        Collections.sort(list, valueComparator);
    }

输出结果:
[cba1=1.1, bca1=2.9, bac1=3.1, acb1=5.1, abc1=10.1, abc2=12.1, cab1=80.1]
获取对应的key, 即cba1,bca1 等等

list.get(i).getKey

2.对list中的类的某个属性的值进行排序

需求:根据timeProportion的大小进行排序

public class InterestStudentLocation implements Comparable<InterestStudentLocation>, Serializable {
    private static final long serialVersionUID = -5411406470341636658L;

    /**
     * 时间占比
     */
    private Double timeProportion;

        public Double getTimeProportion() {
        return timeProportion;
    }

    public void setTimeProportion(Double timeProportion) {
        this.timeProportion = timeProportion;
    }

    @Override
    public int compareTo(InterestStudentLocation o) {
        Double id1 = timeProportion;
        Double id2 = o.getTimeProportion();
        return id1 > id2 ? 1 : id1 == id2 ? 0 : -1;
    }

}
//调用方法查询出list
List<InterestStudentLocation> list = interestStudentLocationDao.getClassLocationAndTime(t);

//对list进行排序
Collections.sort(list);
list就根据timeProportion的大小进行排序了

猜你喜欢

转载自blog.csdn.net/weixin_39297312/article/details/80183033
今日推荐