根據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是無序的