首页 > 编程语言 > 详细

map根据属性排序、取出map前n个

时间:2019-11-04 20:16:36      阅读:694      评论:0      收藏:0      [点我收藏+]
    /**
     * map根据value排序
     * flag = 1 正序
     * flag = 0 倒序
     *
     * @param map
     * @param flag
     * @return
     */
    public static <K, V extends Comparable<? super V>> LinkedHashMap<K, V> sortByValue(Map<K, V> map, int flag) {
        LinkedHashMap<K, V> sortMap = new LinkedHashMap<>();
        if (flag == 1) {
            map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue)).forEach(entry -> sortMap.put(entry.getKey(), entry.getValue()));
        } else {
            map.entrySet().stream().sorted((o1, o2) -> o2.getValue().compareTo(o1.getValue())).forEach(entry -> sortMap.put(entry.getKey(), entry.getValue()));
        }
        return sortMap;
    }

    /**
     * 取出map前n个
     *
     * @param map
     * @param length
     * @return
     */
    @Override
    public LinkedHashMap<String, Double> subMap(LinkedHashMap<String, Double> map, int length) {
        List<Map.Entry<String, Double>> lists = new ArrayList<>(map.entrySet());
        LinkedHashMap<String, Double> sortedMap = new LinkedHashMap<>();
        if (lists.size() >= length) {
            for (Map.Entry<String, Double> set : lists.subList(0, length)) {
                sortedMap.put(set.getKey(), set.getValue());
            }
        } else {
            for (Map.Entry<String, Double> set : lists) {
                sortedMap.put(set.getKey(), set.getValue());
            }
        }
        return sortedMap;
    }

  

map根据属性排序、取出map前n个

原文:https://www.cnblogs.com/sueyyyy/p/11793746.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!