交换和弄平Java地图< integer,list< integer>>>使用流API
拥有此地图< integer,list>:
Map<Integer, List<Integer>> forwardMap = Map.of(
100, List.of(6),
300, List.of(49, 52),
500, List.of(293)
);
我想“弄平”值列表,并在地图中交换键和值,最终以此结束:
Map<Integer, Integer> reverseMap = Map.of(
6, 100,
49, 300
52, 300,
293, 500
);
我的无法编译的尝试,我尝试流式传输set&lt;映射。进入&gt;然后是嵌套列表:
Map<Integer, Integer> reverseMap = forwardMap.entrySet().stream().map(
entry -> entry.getValue().stream().collect(Collectors.toMap(Integer::getInteger, entry.getKey()));
);
也许我需要避免两次使用stream() - 可能是在某个地方使用flatmap()。我还尝试过首先交换键和值 - 但最终仍未引用列表中列表中“外部”键和“内部”嵌套整数的引用。
我想念什么或彻底误解?
Having this Map<Integer, List>:
Map<Integer, List<Integer>> forwardMap = Map.of(
100, List.of(6),
300, List.of(49, 52),
500, List.of(293)
);
I would like to 'flatten' the value Lists and swap the key and value in the Map, ending up with this:
Map<Integer, Integer> reverseMap = Map.of(
6, 100,
49, 300
52, 300,
293, 500
);
My cannot-compile attempt, where I attempt to stream the Set<Map.Entry> and then the nested List:
Map<Integer, Integer> reverseMap = forwardMap.entrySet().stream().map(
entry -> entry.getValue().stream().collect(Collectors.toMap(Integer::getInteger, entry.getKey()));
);
Perhaps I need to avoid using stream() twice - possibly by using flatMap() somewhere and somehow. I have also tried first swapping swapping the key and value - but still end up not having a reference to the 'outer' key and the 'inner' nested Integers in the Lists, at the same time.
What am I missing or downright misunderstanding?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个类似的答案,并添加了一些内容。
(首先,下一个) - &gt; first
合并函数选择了第一个选项。linkedhashmap
以保留排序订单。如果您具有重复的价值并希望保留它,则在这里打印
是如何工作的。唯一的区别是最终收藏家。
groupingby
用于为每个键创建linkedhashmap
的列表,以保留排序的顺序。印刷
Here is a similar answer with a few things added.
(first, next)->first
merge function.LinkedHashMap
to preserve the sorted order.prints
Here is how it would work if you had a duplicate value and wanted to keep it. The only differences are in the final collector.
groupingBy
is used to create a list for each keyLinkedHashMap
is specified to preserve the sorted order.prints
作为目标的一部分,是使值平板,您正确您可能需要在某个地方进行
Flatmap
操作。例如:As part of your goal is to flatten the values, you're correct you'll probably need a
flatMap
operation somewhere. For example: