Java8--Lambda表达式对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是无序的