英文:
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<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));
How do I get a List
out of it?
List<Integer> 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<Integer> 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<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);
And the output is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论