Java Stream将带有列表值的Map转换为一个大列表

huangapple go评论71阅读模式
英文:

Java Stream convert Map with List values to one big list

问题

你可以这样从该Map中获取一个包含 1, 2, 3, 4, 5, 6, 7, 8, 9 元素的List

List<Integer> allnumbers = numbersMap.values()
    .stream()
    .flatMap(List::stream)
    .collect(Collectors.toList());
英文:

I have a Map like this:

Map&lt;String, List&lt;Integer&gt;&gt; numbersMap = new HashMap&lt;&gt;();
numbersMap.put(&quot;A&quot;, Arrays.asList(1,2,3));
numbersMap.put(&quot;B&quot;, Arrays.asList(4,5,6));
numbersMap.put(&quot;C&quot;, Arrays.asList(7,8, 9));

How do I get a List out of it?

List&lt;Integer&gt; allnumbers = //?

that contains 1, 2, 3, 4, 5, 6, 7, 8, 9 elements.

答案1

得分: 4

你可以使用flatMap()将值流式传输,以创建一个流,该流是每个列表流的串联:

List<Integer> allnumbers = numbersMap.values().stream()
   .flatMap(List::stream) // 秘密操作
   .collect(toList());
英文:

You stream the values and use flatMap() to create one stream that is the concatenation of the streams of each List:

List&lt;Integer&gt; allnumbers = numbersMap.values().stream()
   .flatMap(List::stream) // secret sauce
   .collect(toList());

答案2

得分: 3

使用flatMap合并每个列表的流:

Map<String, List<Integer>> numbersMap = new HashMap<>();
numbersMap.put("A", Arrays.asList(1,2,3));
numbersMap.put("B", Arrays.asList(4,5,6));
numbersMap.put("C", Arrays.asList(7,8, 9));

List<Integer> output = numbersMap.values()
                        .stream()
                        .flatMap(list -> list.stream())
                        .collect(Collectors.toList());
System.out.println(output);

输出结果为:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
英文:

use flatMap to merge each list's stream:

Map&lt;String, List&lt;Integer&gt;&gt; numbersMap = new HashMap&lt;&gt;();
numbersMap.put(&quot;A&quot;, Arrays.asList(1,2,3));
numbersMap.put(&quot;B&quot;, Arrays.asList(4,5,6));
numbersMap.put(&quot;C&quot;, Arrays.asList(7,8, 9));

List&lt;Integer&gt; output = numbersMap.values()
						.stream()
						.flatMap(list -&gt; list.stream())
						.collect(Collectors.toList());
System.out.println(output);

And the output is:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

huangapple
  • 本文由 发表于 2020年8月11日 11:37:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63351133.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定