LAST UPDATED: AUGUST 5, 2021
How to join arrays in Java
In this post, we are going to learn to join multiple arrays into a single array using the Java code. There can be a scenario when we need to combine data of two or more arrays into a single array such as combining two sources into one to transport the data as a single source.
Here, we are using Java 8 stream API to joins arrays and get a result as an array or stream. See the given examples here.
Time for an Example:
Let's take an example to join two string arrays into a single string array. Here, we are using of()
method of Stream
that returns a sequence of stream which further is converted into array by using the toArray()
method.
import java.util.stream.Stream;
public class Main {
public static void main(String[] args){
String[] asia = new String[]{"India", "Russia", "Japan"};
String[] europe = new String[]{"Poland", "Germany", "France"};
//join arrays
String[] countries = Stream.of(asia,europe).flatMap(Stream::of).toArray(String[]::new);
for (String country : countries) {
System.out.println(country);
}
}
}
India
Russia
Japan
Poland
Germany
France
Time for another Example:
We can combine two streams by using the concat() method that returns a stream of specified type. The example explains how we can concat two or more stream into a single stream as we did in the above example to combine two arrays.
import java.util.stream.Stream;
public class Main {
public static void main(String[] args){
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);
}
}
1
3
5
2
4
6