Java API中Stream接口的concat()方法
Java API 中的流接口存在于Java.Util.Stream 中,并扩展了 BaseStream
concat() 方法:
该方法的名称表明该方法主要用于将两个流连接在一起。在串联中,第一个流的内容后跟第二个流。最终的输出流可以是有序的或并行的。这基本上取决于输入流。这里要注意这个方法的要点是,当这个连接流关闭时,两个连接流也关闭。
由于一次只能连接两个流,因此可以使用以下想法连接多个流,即首先连接两个流,然后将结果与另一个流连接,以便最后连接所有流。
例子:
let s1=stream 1
s2=stream 2
.
.
.
sn=stream n
so concatenation of all the streams can be shown as :
result stream is = concat(s1,concat(s2,concat(………).))
hence the resulting stream has all the streams in the order s1s2s3s4s5s6……sn.
该方法的声明语法如下所示。
static
Here we are having two streams of type T namely A and B. Also the main thing to notice here is that this method is a static method.
下面是问题陈述的实现:
示例 1:
Java
// Implementation of concat() method
// of Stream interface in Java API
import java.util.*;
// importing the necessary classes to
// implement the stream interface
import java.util.stream.Stream;
// save as file named GFG2.java
public class GFG2 {
// main method
public static void main(String[] args) throws Exception
{
// first stream
Stream s1 = Stream.of(1, 2, 3, 4);
// second stream
Stream s2 = Stream.of(5, 6, 7, 8);
// concatenation and printing
// of the stream elements.
Stream.concat(s1, s2).distinct().forEach(
ele -> System.out.println(ele));
}
}
Java
// Implementation of concat() method
// of Stream interface in Java API
import java.util.*;
import java.util.stream.DoubleStream;
// importing the necessary classes
// to implement the stream interface
import java.util.stream.Stream;
// save as file named GFG2.java
public class GFG2 {
// main method
public static void main(String[] args) throws Exception
{
// first stream
DoubleStream s1
= DoubleStream.of(1.025, 2.0687, 3.01);
// second stream
DoubleStream s2 = DoubleStream.of(5.2587410, 8);
// concatenation and printing
// of the stream elements.
DoubleStream.concat(s1, s2).distinct().forEach(
ele -> System.out.println(ele));
}
}
1
2
3
4
5
6
7
8
示例 2:
Java
// Implementation of concat() method
// of Stream interface in Java API
import java.util.*;
import java.util.stream.DoubleStream;
// importing the necessary classes
// to implement the stream interface
import java.util.stream.Stream;
// save as file named GFG2.java
public class GFG2 {
// main method
public static void main(String[] args) throws Exception
{
// first stream
DoubleStream s1
= DoubleStream.of(1.025, 2.0687, 3.01);
// second stream
DoubleStream s2 = DoubleStream.of(5.2587410, 8);
// concatenation and printing
// of the stream elements.
DoubleStream.concat(s1, s2).distinct().forEach(
ele -> System.out.println(ele));
}
}
1.025
2.0687
3.01
5.258741
8.0
以同样的方式,我们可以拥有不同类型的流,例如用于字符串、用于 char 等等。