Java 8 Array Join – How to join arrays in java using stream API

1 month ago Lalit Bhagtani 0

Java 8 Array Join

In this tutorial, we will learn about how to join (merge) two or more arrays in Java 8 using Stream API.

Java Array Join

Problem Statement

Given an arrays of string data type, merge them together and print all of its values. To implement this, we will use Stream Class of Stream API.

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

public class MergeArrays {

  public static void main(String[] args) {
		
     String[] s1 = new String[]{"a", "b", "c", "d"};
     String[] s2 = new String[]{"e", "f", "g", "h"};
     String[] s3 = new String[]{"i", "j", "k", "l"};

     /* joining 3 String object type arrays */
     String[] result = Stream.concat(Stream.of(s1), Stream.concat(Stream.of(s2), Stream.of(s3))).toArray(String[]::new);
        
     System.out.println(Arrays.toString(result));

     int[] int1 = new int[]{1,2,3};
     int[] int2 = new int[]{4,5,6};

     /* joining 2 int primitive type arrays */
     int[] result2 = IntStream.concat(Arrays.stream(int1), Arrays.stream(int2)).toArray();

     System.out.println(Arrays.toString(result2));

  }

}

Result :- 

[a, b, c, d, e, f, g, h, i, j, k, l]
[1, 2, 3, 4, 5, 6]

References :- 

  1. IntStream JavaDocs
  2. Stream JavaDocs

That’s all for how to join (merge) two or more arrays in Java 8 using Stream API. If you liked it, please share your thoughts in comments section and share it with others too.