如何在不使用foreach的情况下合并两个列表? [英] How to combine two lists without using foreach?
问题描述
最初,我有以下代码:
String[] A;
String[] B;
//...
List<String> myList= new ArrayList<>(A.length + B.length);
for (int i= 0; i< B.length; i++){
myList.add(A[i]);
myList.add("*".equals(B[i]) ? B[i] : doSomethingWith(B[i]));
}
如果最好使用Java 8,如何重构?
How to refactor if using, preferably, Java 8?
例如,如果我有这些数组
If for instance I have these arrays
A = {一个",两个",三个",四个"}
B = {五个",六个",七个",八个"}
在代码结尾,myList将为:
At the end of the code, myList will be:
myList = {一个",五个",两个",六个",三个",七个",四个",八个"}
推荐答案
我个人认为这不需要进行重构,因为任何流式"代码都不会比您现有的代码更具可读性和直观性,但是作为一个纯粹的证明,概念:
I personally don't think this needs refactoring as any "streamed" code will be less readable and less intuitive than your existing code, but as a pure proof-of-concept:
String[] A;
String[] B;
List<String> myList;
myList = IntStream.range(0, B.length)
.mapToObj(i -> new String[]
{
A[i],
"*".equals(B[i]) ? B[i] : doSomethingWith(B[i])
})
.flatMap(Arrays::stream)
.collect(Collectors.toList());
工作演示.
-
我们使用
IntStream.range
将索引提供到数组中.
We use
IntStream.range
to provide the indices into our arrays.
mapToObj
将每个索引映射到包含我们想要的元素的数组(也需要此阶段,因为IntStream::flatMap
只能转换为另一个IntStream
,我们希望将其转换为Stream
String
s).
mapToObj
maps each index to an array containing the elements we want (this stage is also needed as IntStream::flatMap
can only convert to another IntStream
, we want to convert it to a Stream
of String
s).
flatMap
将每个数组映射到一个流,然后展平"所得的流.
flatMap
maps each array to a stream, then "flattens" the resulting stream of streams.
最后,我们只是collect
结果.
这篇关于如何在不使用foreach的情况下合并两个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!