使用Java 8 Stream按Map的键进行排序
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(15, "Mahesh");
map.put(10, "Suresh");
map.put(30, "Nilesh");
Map<Integer, String> map1 = new HashMap<Integer, String>();
// 按照Map的键进行排序
map1 = map.entrySet().stream().sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap
(Map.Entry::getKey,
Map.Entry::getValue,(oldVal,newVal)->oldVal, LinkedHashMap::new));
for (Map.Entry e : map1.entrySet()){
System.out.println("Key: " + e.getKey() + ", Value: " + e.getValue());
}
}
控制台日志