标签:选择 tom com res sed 冲突 set reverse key
LinkedHashMap<String,User> result =
//方法一
map.entrySet().stream()
//根据User中某个字段进行排序
.sorted(Map.Entry.comparingByValue(
//若为Map<String,String>,则不需要下面这段
Comparator.comparing(User::getAge)
)
//加上为倒序,去掉则为升序
.reversed())
.collect(Collectors.toMap
(
Map.Entry::getKey,
Map.Entry::getValue,
//当相同key值冲突时,取老的值进行覆盖(是否选择新老值,取决于业务)
(oldValue, newValue) -> oldValue,
LinkedHashMap::new
));
//方法二,不推荐
/*map.entrySet().stream()
.sorted(
Map.Entry.<String,User>comparingByValue(Comparator.comparing(User::getAge))
//加上为倒序,去掉则为升序
.reversed() )
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));*/
标签:选择 tom com res sed 冲突 set reverse key
原文地址:https://www.cnblogs.com/kony23/p/14377495.html