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

    /**
     * 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;
    }

  

posted @ 2019-11-04 18:12  少说点话  阅读(1493)  评论(0编辑  收藏  举报
网站运行: