In this tutorial, I am going to show you how to concatenate arrays using Java8 streams.
Java8 Concatenate Arrays :
Array_Concatinate.java
import java.util.Arrays;
import java.util.stream.Stream;
public class Array_Concatinate {
public static void main(String[] args) {
String[] alphabets = { "AB", "BA", "AC" };
String[] numarics = { "1", "2", "3" };
String[] both = Stream.concat(Arrays.stream(alphabets),
Arrays.stream(numarics)).toArray(String[]::new);
for (String string : both) {
System.out.println(string);
}
}
}
Output:
Terminal
AB
BA
AC
1
2
3
Concatenate Arrays using flatMap:
Array_Concatinate.java
import java.util.stream.Stream;
public class Array_Concatinate {
public static void main(String[] args) {
String[] alphabets = { "AB", "BA", "AC" };
String[] numarics = { "1", "2", "3" };
String[] both = Stream.of(alphabets, numarics).flatMap(Stream::of)
.toArray(String[]::new);
for (String string : both) {
System.out.println(string);
}
}
}
[/java]
Output:
Terminal
AB
BA
AC
1
2
3
Concatenate using Java API:
Array_Concatinate.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Array_Concatinate {
public static void main(String[] args) {
String[] alphabets = { "AB", "BA", "AC" };
String[] numarics = { "1", "2", "3" };
List<String> both = new ArrayList<String>(alphabets.length
+ numarics.length);
Collections.addAll(both, alphabets);
Collections.addAll(both, numarics);
String[] strArray = both.toArray(new String[both.size()]);
for (String string : strArray) {
System.out.println(string);
}
}
}
Output:
Terminal
AB
BA
AC
1
2
3
Happy Learning 🙂