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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM