How to Join Two Arrays in Java using Stream API?

We can first convert the Arrays into IntStream and then make use of the IntStream.concat method to add two Arrays in Java.


Example:

import java.util.Arrays;
import java.util.stream.IntStream;

public class Example {

    public static void main(String[] args) {

        int[] numArray1 = {1, 2, 3, 4, 5};
        int[] numArray2 = {6, 7, 8, 9, 10};
        IntStream intStream1 = Arrays.stream(numArray1);
        IntStream intStream2 = Arrays.stream(numArray2);

        int[] result = IntStream.concat(intStream1, intStream2).toArray();

        for (int element : result) {
            System.out.print(element + " ");
        }
    }
}

Output:

1 2 3 4 5 6 7 8 9 10

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!