在地图中将所有列表值合并在一起 [英] Merge all list values together in a map

查看:173
本文介绍了在地图中将所有列表值合并在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将地图转换为:

Map<String, List<String>> 

List<String> 

其中结果列表是所有List值的合并。

where the result list is the merge of all List values.

推荐答案

你可以

List<String> result = map.values().stream().flatMap(List::stream).collect(Collectors.toList());

这将使用 values() 然后持平将每个列表映射到由其元素组成的Stream中,并将结果收集到列表中。

This retrieves the values of the map with values() then flat maps each list into a Stream formed by its elements and collects the result into a list.

另一个替代方案,没有平面映射每个列表,因此可能更高性能,是直接收集流< List< String>> (由 values()。stream())返回在每个累计结果上调用 addAll

Another alternative, without flat mapping each list, and thus may be more performant, is to collect directly the Stream<List<String>> (returned by values().stream()) by calling addAll on each accumulated result.

List<String> result = map.values().stream().collect(ArrayList::new, List::addAll, List::addAll);

这篇关于在地图中将所有列表值合并在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆