Java 8要映射的对象列表< String,List>价值的

问题描述:

我正在尝试使用StreamsList<Object>转换为Map<String, List>

I am trying to convert List<Object> to Map<String, List> using 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)

to be use in named query -> eg: 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());

如何仅在一次流式传输到列表时收集所有值?

How to collect all the values while streaming to the list only once ?

我相信这样应该可以:

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个必需属性),然后通过其键将所有用户映射的条目分组.

It converts each User to a Map<String,String> (containing the 3 required properties indexed by the required keys), and then groups the entries of all the user maps by their keys.

这是直接创建Map.Entry而不是创建小的HashMap的另一种选择,因此它应该更有效:

Here's another alternative that creates the Map.Entrys directly instead of creating the small HashMaps, so it should be more efficient:

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())));