假设我有一个Map<Integer, Map<Class, String>>
,如何在一个优雅(但可能很长)的Integer
流声明中获得外部映射的Java键和所有映射的键的所有组合?
我的方法:
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
的集合。当然,这种方法可能是完全错误的。
我的问题是我根本找不到解决这个问题的方法。请注意,我不是在寻找解决办法,因为我想扩大我的理解。
发布于 2018-08-15 05:41:41
你就快到了。你只需要一个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()
https://stackoverflow.com/questions/51850108
复制相似问题