如何将这个包装地图列表展平为另一种地图 Java 8?

How to flatten this list of wrapped maps into a different kind of map Java 8?

我无法弄清楚如何清理我的一些代码来执行此操作:

我有一个 Context 对象的列表。每个 Context 都有一个 String userId 和一个 Map<String, SomeObject> someObjects.

我想将其扁平化为 Map<String, SomeObjects>,其中 kep 是 userId。更具体地说:

class Context {
    String userId;
    Map<String, List<SomeObject>> // the String here is something other than userId
    // other stuff, getters/setters
}

给定 List<Context>,我想得到 Map<String, List<SomeObject> 但字符串实际上是 userId。

有没有一种干净的方法可以做到这一点?

正在创建 class 上下文以保存 StringMap 数据类型

class Context {
    String userId;
    Map<String, List<Integer>> map;

    public Context(String s, List<Integer> list) {
        userId = s;
        map = new HashMap<>();
        map.put(userId, list);
    }

    public void setValues(String s, List<Integer> list) {
        map.put(s, list);
    }

}

现在创建解决方案 class,其中包含 List<Context>

public class Solution {

    public static void main(String[] args) {

        List<Integer> list;

        // Context c1
        list = new ArrayList<>(Arrays.asList(1, 2, 3));
        Context c1 = new Context("dev", list);

        list = new ArrayList<>(Arrays.asList(-1, -3));
        c1.setValues("dev2", list);

        list = new ArrayList<>(Arrays.asList(-6, -3));
        c1.setValues("dev3", list);

        // Context c2
        list = new ArrayList<>(Arrays.asList(12, 15, 18));
        Context c2 = new Context("macy", list);

        list = new ArrayList<>(Arrays.asList(-12, -13));
        c2.setValues("macy2", list);

        list = new ArrayList<>(Arrays.asList(-8, -18));
        c2.setValues("macy3", list);

        // Context c3
        list = new ArrayList<>(Arrays.asList(20, 30));
        Context c3 = new Context("bob", list);

        list = new ArrayList<>(Arrays.asList(-31, -32));
        c3.setValues("bob2", list);

        // Context List
        List<Context> contextList = new ArrayList<>();
        contextList.addAll(Arrays.asList(c1, c2, c3));

        retrieveRecords(contextList);
    }

    private static void retrieveRecords(List<Context> contextList) {
        // regular way of retrieving map values
        for (Context c : contextList) {
            System.out.println(c.map);
        }

        System.out.println();

        // Retrieving only those records which has String key as userID
        for (Context c : contextList) {
            System.out.println(c.userId + "\t=>\t" + c.map.get(c.userId));
        }
    }

}

假设 Context 有一个 String userid 和一个 List<SomeObject> someObjects:

Map<String, Set<SomeObject>> map = contexts.stream()
    .collect(Collectors.toMap(Context::getUserid, 
       c -> c.getSomeObjects().values().stream()
      .flatMap(Collection::stream)
      .collect(Collectors.toSet())
     ));

这里的重点是使用toMap() to collect by userid and flatmap()把一个Stream<List<SomeObject>>变成一个Stream<SomeObject>,这样你就可以把它们合为一个集合了。