Java8 Concatenate Arrays Example using Stream

By | 2017-12-11T09:06:59+00:00 December 11th, 2017|java8|0 Comments

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 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment