IntStream concat()方法创建一个级联流,其中的元素是第一个流的所有元素,后跟第二个流的所有元素。如果两个输入流都是有序的,则结果流是有序的;如果两个输入流中的任何一个是并行的,则结果流是并行的。
用法:
static IntStream concat(IntStream a, IntStream b)
Where, IntStream is a sequence of primitive int-valued elements,
a represents the first stream,
b represents the second stream and
the function returns the concatenation of
the two input IntStreams.
可以将对IntStream.concat(IntStream a,IntStream b)的调用视为形成二叉树。所有输入流的串联都在根。各个输入流位于叶子处。下面给出的是3个IntStream a,b和c的示例。
每个附加的输入流为树增加了一层深度,并为所有其他流增加了一层间接。
注意:IntStream.concat()方法返回的元素是有序的。例如,以下两行返回相同的结果:
IntStream.concat(IntStream.concat(stream1, stream2), stream3);
IntStream.concat(stream1, IntStream.concat(stream2, stream3));
但是以下两个结果是不同的。
IntStream.concat(IntStream.concat(stream1, stream2), stream3);
IntStream.concat(IntStream.concat(stream2, stream1), stream3);
示例1:
// Implementation of IntStream.concat()
// method in Java 8 with 2 IntStreams
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating two IntStreams
IntStream stream1 = IntStream.of(2, 4, 6);
IntStream stream2 = IntStream.of(1, 3, 5);
// concatenating both the Streams
// with IntStream.concat() function
// and displaying the result
IntStream.concat(stream1, stream2)
.forEach(element -> System.out.println(element));
}
}
输出:
2
4
6
1
3
5
示例2:
// Implementation of IntStream.concat()
// method in Java 8 with 2 IntStreams
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating two IntStreams
IntStream stream1 = IntStream.of(2, 4, 6);
IntStream stream2 = IntStream.of(1, 2, 4);
// concatenating both the Streams
// with IntStream.concat() function
// and displaying distinct elements
// in the concatenated IntStream
IntStream.concat(stream1, stream2).distinct().
forEach(element -> System.out.println(element));
}
}
输出:
2
4
6
1