Java8--Lambada表達式對Map的操作


根據Map的鍵名、鍵值進行升序、降序:

public class StudyMap {
 
         
     public static void main(String[] args) {
        Map<String, Integer> wordCounts = new HashMap<>();
        wordCounts.put("USA", 100);
        wordCounts.put("jobs", 200);
        wordCounts.put("software", 50);
        wordCounts.put("technology", 70);
        wordCounts.put("opportunity", 200);


        //按升序對值進行排序,使用LinkedHashMap存儲排序結果來保留結果映射中元素的順序
        Map<String, Integer> sortedByCount = wordCounts.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
        soutMap(sortedByCount);

        //sorted()方法將Comparator作為參數使用任何類型的值對映射進行排序。上面的排序可以用Comparator寫成:
        //正向
        Map<String, Integer> sortedByCount3 = wordCounts.entrySet()
                .stream()
                .sorted((e1, e2) -> e1.getValue().compareTo(e2.getValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
        soutMap(sortedByCount3);

        //反向 == reversed()
        Map<String, Integer> sortedByCount2 = wordCounts.entrySet()
                .stream()
                .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
        soutMap(sortedByCount2);

    }

    public static void soutMap(Map<String, Integer> sortedByCount){
        for (Map.Entry<String, Integer> entry : sortedByCount.entrySet()) {
            System.out.println("key:" + entry.getKey()+"\tvalue:"+entry.getValue());
        }
    }
}

在上述代碼中對於map的重新轉換,建議轉換成LinkedHashMap,因為HashMap是無序的


免責聲明!

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



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