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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap