Introduction
In Java, it is often necessary to combine two or more arrays into a single array. This can be achieved using Java 8 stream API. In this lab, we will learn how to join multiple arrays into a single array using the Java code.
In Java, it is often necessary to combine two or more arrays into a single array. This can be achieved using Java 8 stream API. In this lab, we will learn how to join multiple arrays into a single array using the Java code.
First, create a Java file named ArraysJoin.java in the ~/project/
directory by using the following command:
touch ~/project/ArraysJoin.java
Import the required library for using Java 8 stream API.
import java.util.stream.Stream;
Define two arrays that you want to join. Here, we are taking two string arrays asia
and europe
.
String[] asia = new String[]{"India", "Russia", "Japan"};
String[] europe = new String[]{"Poland", "Germany", "France"};
Now, initialize a new array that is a combination of both arrays using the Java 8 Stream API.
String[] countries = Stream.of(asia,europe).flatMap(Stream::of).toArray(String[]::new);
In the above example, the flatMap()
method is used to merge two arrays and convert them into a stream of strings, and the toArray()
method converts the stream into an array of strings.
Finally, print the joined array elements using a for loop.
for (String country : countries) {
System.out.println(country);
}
We can also merge two streams by using the concat()
method that returns a stream of specified type. The example shows how we can concatenate two or more streams into a single stream.
Stream<Integer> stream1 = Stream.of(1, 2, 3);
Stream<Integer> stream2 = Stream.of(4, 5, 6);
//concat arrays
Stream<Integer> result = Stream.concat(stream1, stream2);
result.forEach(System.out::println);
Compile the Java file using the following command:
javac ~/project/ArraysJoin.java
Run the Java program using the following command:
java -cp ~/project ArraysJoin
Output:
India
Russia
Japan
Poland
Germany
France
1
2
3
4
5
6
In this lab, we learned how to join multiple arrays into a single array using the Java 8 stream API. We also learned how to concatenate multiple streams into a single stream. The concept of joining and concatenating arrays and streams is used in programming when dealing with large amounts of data that needs to be stored in a single source platform.