我正在尝试使用List<Object>
将Map<String, List>
转换为Streams
,
public class User{
String name;
String age;
String org;
}
我有
List<Users>
,需要收集到Map<String, Object> m
中, m.put("names", List of names,);
m.put("age", List of age);
m.put("org", List of org);
用于命名查询->例如:
select * from table ... where names in (:names) and age in (:age) and org in (:org)
截至目前,我的行为
List<String> names = userList.stream().map(User::getName).collect(Collectors.toList());
List<String> age= userList.stream().map(User::getAge).collect(Collectors.toList());
List<String> org= userList.stream().map(User::getName).collect(Collectors.toList());
如何仅一次流式传输到列表时收集所有值?
最佳答案
我相信这样的事情应该起作用:
Map<String,List<String>> map =
userList.stream()
.flatMap(user -> {
Map<String,String> um = new HashMap<>();
um.put("names",user.getName());
um.put("age",user.getAge());
um.put("org",user.getOrg());
return um.entrySet().stream();
}) // produces a Stream<Map.Entry<String,String>>
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue,
Collectors.toList())));
它将每个
User
转换为Map<String,String>
(包含由必需键索引的3个必需属性),然后按其键对所有用户映射的条目进行分组。编辑:
这是另一种直接创建
Map.Entry
而不是创建小的HashMap
的替代方法,因此它应该更有效:Map<String,List<String>> map =
userList.stream()
.flatMap (user -> Stream.of (new SimpleEntry<>("names",user.getName()),
new SimpleEntry<>("age",user.getAge()),
new SimpleEntry<>("org",user.getOrg())))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue,
Collectors.toList())));