繁体   English   中英

如何将这个包装的地图列表压缩成另一种地图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>但是String实际上是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()通过useridflatmap()Stream<List<SomeObject>>转换为Stream<SomeObject>以便将它们收集到一个集合中。

创建类Context以保存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);
    }

}

现在创建具有List<Context>的Solution类

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

}

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM