Map<String,String> map1 = new HashMap<>();
map1.put("a","123");
map1.put("b","456");
map1.put("z","789");
map1.put("c","234");
1、默认顺序
List<UserInfo> list0 = map1.entrySet().stream()
.map(e -> new UserInfo(e.getValue(), e.getKey()))
.collect(Collectors.toList());
结果:[UserInfo(userName=123, mobile=a), UserInfo(userName=456, mobile=b), UserInfo(userName=234, mobile=c), UserInfo(userName=789, mobile=z)]
2、根据Key排序
List<UserInfo> list1 = map1.entrySet().stream()
.sorted(Comparator.comparing(e -> e.getKey()))
.map(e -> new UserInfo(e.getKey(), e.getValue()))
.collect(Collectors.toList());
结果:[UserInfo(userName=a, mobile=123), UserInfo(userName=b, mobile=456), UserInfo(userName=c, mobile=234), UserInfo(userName=z, mobile=789)]
3、根据Value排序
List<UserInfo> list2 = map1.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getValue))
.map(e -> new UserInfo(e.getKey(), e.getValue()))
.collect(Collectors.toList());
结果:[UserInfo(userName=a, mobile=123), UserInfo(userName=c, mobile=234), UserInfo(userName=b, mobile=456), UserInfo(userName=z, mobile=789)]
3、根据Key排序
List<UserInfo> list3 = map1.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.map(e -> new UserInfo(e.getKey(), e.getValue()))
.collect(Collectors.toList());
结果:[UserInfo(userName=a, mobile=123), UserInfo(userName=b, mobile=456), UserInfo(userName=c, mobile=234), UserInfo(userName=z, mobile=789)]
4、Map<String,UserInfo> 转 List<String>、List<UserInfo>
// 取Map中的所有value
结果:List<UserInfo> userInfoList = retMap.values().stream().collect(Collectors.toList());
// 取Map中所有key
结果:List<String> strList = retMap.keySet().stream().collect(Collectors.toList());