In this tutorial, I am going to show you how to concatenate arrays using Java8 streams.

Java8 Concatenate Arrays :


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);
        }
    }
}

[box type=”success” align=”alignleft” class=”” width=”100%”]

AB
BA
AC
1
2
3

[/box]

Concatenate Arrays using flatMap:


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);
        }
    }
}

[box type=”success” align=”alignleft” class=”” width=”100%”]

AB
BA
AC
1
2
3

[/box]

Concatenate using Java API:


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);
        }
    }
}

[box type=”success” align=”alignleft” class=”” width=”100%”]

AB
BA
AC
1
2
3

[/box]

Happy Learning 🙂