List Java 8中2个字符串的每个组合 [英] Every combination of 2 strings in List Java 8
问题描述
我想组合列表中的每两个字符串,并使用java8流返回组合列表:
I would like to combine every two strings in the list and return the list of combination using java8 streams:
List<String> list;
Stream.concat(list.stream(), list.stream())
.collect(toList());
但是,此代码不会产生组合,而只会产生列表中的元素.我究竟做错了什么.我还希望此代码可以并行化,以便可以在多个内核上运行
However this code doesn't produce combinations but just elements of the lists. What am I doing wrong. I would also like this code to be parallelized so it can run on multiple cores
推荐答案
Use flatMap
to combine the strings in a combinatoric manner. Each string will be concatenated with each string in the list.
List<String> combinations =
list.stream()
.flatMap(str1 -> list.stream().map(str2 -> str1 + str2))
.collect(toList());
要使操作并行,请将.stream()
换为.parallelStream()
.根据您输入的大小,这可能会使操作变慢或变快.
To make the operations parallel, swap out .stream()
for .parallelStream()
. Depending on your input size, this may make the operation slower or faster.
这篇关于List Java 8中2个字符串的每个组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!