-
场景描述
在工作中,经常会遇到这种情形:两组list信息,list1要使用list2的信息
比如:用户users,部门departments,需要获取用户具体的部门信息 -
实现
- 使用for循环,这个应该都会
for (Department department: departments) { maps.put(department.getId(), department); }
- 另一种就是使用stream
Map<Long, Department > maps = departments .stream().collect(Collectors.toMap(Department::getId, a->a, (key1, key2) -> key2)); //map的key: Department::getId // map的value: a->a (也有人用Function.identity()代替) // 防止有重复数据,产生报错,(key1, key2) -> key2 :有重复选新的
-
list 转Map<String, List<Map<String, Object>>>
Map<String, List<Map<String, Object>>> users = allUsers .stream().collect(Collectors.groupingBy(a -> a.getDepartment(), Collectors.mapping(a -> { Map<String, Object> user = new HashMap<>(); user.put("value", a.getUserid()); user.put("name", a.getName()); user.put("type","user"); return user; }, Collectors.toList())));
注意:
Function.identity()这个不能代替基本类型
看源码就知道了,泛型参数只能是对象:
static <T> Function<T, T> identity() {
return t -> t;
}
- 结尾
- 关于stream 流还有很多用法,我这边就不多累述了。
广告推广: