Java program to concatenate two arrays using Stream API
Program
import java.util.stream.Stream;
import java.util.Arrays;
import java.util.Scanner;
public class ConcatenateTwoArraysUsingStreamAPI {
public static <T> Object[] mergeArray(T[] array1, T[] array2) {
return Stream.of(array1, array2).flatMap(Stream::of).toArray();
}
public static void main(String[] args) {
int i;
System.out.println("Enter the required size of the first array: ");
Scanner reader = new Scanner(System.in);
int size = reader.nextInt();
String inputFirstArray[] = new String[size];
System.out.println("Enter the elements of the array: ");
for (i = 0; i < inputFirstArray.length; i++) {
inputFirstArray[i] = reader.next();
}
System.out.println("Enter the required size of the second array: ");
size = reader.nextInt();
String inputSecondArray[] = new String[size];
System.out.println("Enter the elements of the array: ");
for (i = 0; i < inputSecondArray.length; i++) {
inputSecondArray[i] = reader.next();
}
Object[] mergedArray = mergeArray(inputFirstArray,inputSecondArray);
System.out.println("Arrays after merging: ");
System.out.println(Arrays.toString(mergedArray));
}
}
Output
javac .\ConcatenateTwoArraysUsingStreamAPI.java
java ConcatenateTwoArraysUsingStreamAPI
Enter the required size of the first array:
3
Enter the elements of the array:
oodlescoop
tutorials
programs
Enter the required size of the second array:
2
Enter the elements of the array:
recipes
travel
Arrays after merging:
[oodlescoop, tutorials, programs, recipes, travel]