Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Stream.concat() in Java
The concat() method of the Stream class in Java creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream. The syntax is as follows −
concat(Stream extends T> a, Stream extends T> b)
Here, a is the first stream, whereas b is the second stream. T is the type of stream elements.
Example
Following is an example to implement the concat() method of the Stream class −
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Demo {
public static void main(String[] args) {
Stream streamOne = Stream.of("John");
Stream streamTwo = Stream.of("Tom");
Stream.concat(streamOne, streamTwo).forEach(val -> System.out.println(val));
}
}
Output
John Tom
Example
Let us now see another example wherein we are working on multiple streams −
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.stream.Stream.*;
public class Main {
public static void main(String[] args) {
Stream streamOne = Stream.of(15, 40, 50);
Stream streamTwo = Stream.of(55, 70, 90);
Stream streamThree = Stream.of(110, 130, 150);
Stream streamFour = Stream.of(170, 200, 240, 300);
Stream res = Stream.concat(streamOne, concat(streamTwo, concat(streamThree, streamFour)));
System.out.println( res.collect(Collectors.toList()) );
}
}
Output
[15, 40, 50, 55, 70, 90, 110, 130, 150, 170, 200, 240, 300]
Advertisements
