代码之家  ›  专栏  ›  技术社区  ›  Kalle Richter

如何获得嵌套映射的所有键与Java流的组合?

  •  1
  • Kalle Richter  · 技术社区  · 6 年前

    Map<Integer, Map<Class, String>> 我怎么能得到 Integer

    我的方法:

    Map<Integer, Map<Class, String>> map = new HashMap<>();
    map.keySet().stream()
            .map(intKey -> map.get(intKey).keySet().stream()
                    .map(classKey -> new SimpleEntry(intKey, classKey)))
            .collect(Collectors.toList());
    

    收集 java.util.stream.ReferencePipeline

    map.keySet().stream()
            .map(intKey -> map.get(intKey).keySet().stream()
                    .map(classKey -> new SimpleEntry(intKey, classKey))
                    .collect(Collectors.toList()))
            .collect(Collectors.toList());
    

    我很难把我的头绕在已经收集的 SimpleEntry

    我的问题是我根本找不到解决这个问题的方法。请注意,我不是在寻找解决办法,因为我想扩大我的理解。

    1 回复  |  直到 6 年前
        1
  •  2
  •   shmosel    6 年前

    你就快到了。你只需要一个 flatMap()

    map.entrySet()
            .stream()
            .flatMap(e -> e.getValue()
                    .keySet()
                    .stream()
                    .map(c -> new SimpleEntry<>(e.getKey(), c)))
            .collect(Collectors.toList())
    

    只是为了好玩,这是 StreamEx

    EntryStream.of(map)
            .mapValues(Map::keySet)
            .flatMapValues(Set::stream)
            .toList()