Java中的 IntStream concat()
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 个 IntStreams 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