话不多说,直接上代码:
@Test
public void mapLambdaTest(){
Map<String,Integer> map = new LinkedHashMap<>();
map.put("张三",50);
map.put("李四",60);
map.put("王五",30);
map.put("赵六",10);
//如果想根据map的key进行排序的话只需要将comparingByValue 更改为comparingByKey()即可
map.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEachOrdered(user -> {
map.remove(user.getKey());
map.put(user.getKey(),(user.getValue()));
});
System.out.println("正序"+map);
//同理:如果想根据map的key进行排序的话只需要将getValue 更改为getKey()即可
map.entrySet().stream().sorted((o1, o2) -> o2.getValue().compareTo(o1.getValue()))
.forEach(user -> {
map.remove(user.getKey());
map.put(user.getKey(), user.getValue());
});
System.out.println("倒序"+map);
}
附加结果图: