List转Map
Map<Integer, User> map = list.stream().collect(Collectors.toMap(User::getId, t -> t, (oldData, newData) -> newData));
Map<Integer, String> map2 = list.stream().collect(Collectors.toMap(User::getId, User::getName, (oldData, newData) -> newData));
当集合对象key重复时可根据(oldData, newData) -> newData
设置保留新值还是旧值,这里是保留新值。
List对象转Map<String, List<对象>>
Map<String, List<User>> map = Maps.newHashMap();
List<User> list = this.list();
if (CollectionUtils.isEmpty(list)) {
return map;
}
for (User item : list) {
map.computeIfAbsent(item.getCode(), k -> new LinkedList<>()).add(item);
}
Map转List
List<User> list = map.entrySet().stream()
.map(
e -> User.builder().id(e.getKey()).name(e.getValue()).build()
)
.collect(Collectors.toList());