Pages

Sunday, November 15, 2020

Java Program To Concatenate Two Arrays (+Java 8 Streams)

1. Introduction


In this article, You'll be learning today how to merge or concatenate two or more arrays into a single array. Input arrays can be primitive or String arrays. All examples that are going to learn today will be working with any type of input.

Let us go and dive into the methods to join two arrays in java.


  • Java API
  • Java 8 Stream API
  • Apache Commons Lang Library


Java Program To Concatenate Two Arrays (+Java 8 Streams)

Java 8 - Merge Two Arrays




2. Java API - System.arraycopy() to join two Arrays


Let us implement a program using a simple core java api class System and its method arraycopy().
This program works well with primitive and wrapper arrays.

How to copy an array from another using System.arraycopy() method ?

Written a dedicated method for int[] arrays.

package com.javaprogramto.arrays.join;

import java.lang.reflect.Array;
import java.util.Arrays;

public class ArraysJoinArrayCopy {

    public static void main(String[] args) {

        String[] s1 = new String[]{"Aa", "Bb", "Cc"};
        String[] s2 = new String[]{"Dd", "Ee", "Ff"};
        String[] s3 = new String[]{"Gg", "Hh", "Ii"};

        String[] result = joinArrayGeneric(s1, s2, s3);

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

        int[] int1 = new int[]{10, 20, 30};
        int[] int2 = new int[]{40, 50, 60};
        int[] int3 = new int[]{70, 80, 90};

        int[] result2 = joinArray(int1, int2, int3);

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

    /**     * This works for all types of primitive and String as well as for wrapper classes.     *     * @param arrays     * @param <T>     * @return     */    static <T> T[] joinArrayGeneric(T[]... arrays) {
        int length = 0;
        for (T[] array : arrays) {
            length += array.length;
        }

        //T[] result = new T[length];        final T[] result = (T[]) Array.newInstance(arrays[0].getClass().getComponentType(), length);

        int offset = 0;
        for (T[] array : arrays) {
            System.arraycopy(array, 0, result, offset, array.length);
            offset += array.length;
        }

        return result;
    }

    static int[] joinArray(int[]... arrays) {
        int length = 0;
        for (int[] array : arrays) {
            length += array.length;
        }

        final int[] result = new int[length];

        int offset = 0;
        for (int[] array : arrays) {
            System.arraycopy(array, 0, result, offset, array.length);
            offset += array.length;
        }

        return result;
    }

}

Output:

[Aa, Bb, Cc, Dd, Ee, Ff, Gg, Hh, Ii]
[10, 20, 30, 40, 50, 60, 70, 80, 90]

3. Java 8 Stream Program to Join Arrays


package com.javaprogramto.arrays.join;

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

public class Java8JoinArrays {

    public static void main(String[] args) {
        String[] s1 = new String[]{"Aa", "Bb", "Cc"};
        String[] s2 = new String[]{"Dd", "Ee", "Ff"};
        String[] s3 = new String[]{"Gg", "Hh", "Ii"};

        //join object type array        String[] result = Stream.of(s1, s2, s3).flatMap(Stream::of).toArray(String[]::new);
        System.out.println("String join : "+Arrays.toString(result));

        int[] int1 = new int[]{10, 20, 30};
        int[] int2 = new int[]{40, 50, 60};
        int[] int3 = new int[]{70, 80, 90};

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

        //join 3 primitive type array, any better idea?        int[] result3 = IntStream.concat(Arrays.stream(int1),
                IntStream.concat(Arrays.stream(int2), Arrays.stream(int3))).toArray();

        System.out.println("Two Int array's join : "+Arrays.toString(result2));

        System.out.println("Three Int array's join : "+Arrays.toString(result3));
    }
}

Output:

String join : [Aa, Bb, Cc, Dd, Ee, Ff, Gg, Hh, Ii]
Two Int array's join : [10, 20, 30, 40, 50, 60]
Three Int array's join : [10, 20, 30, 40, 50, 60, 70, 80, 90]

4. Apache Utils - ArraysUtil.addAll() Example To Add Arrays


package com.javaprogramto.arrays.join;


import org.apache.commons.lang3.ArrayUtils;

import java.util.Arrays;

public class ApacheJoinArrays {
    public static void main(String[] args) {

        String[] s1 = new String[]{"hello", "boss", "welcome"};
        String[] s2 = new String[]{"nice", "to", "meet", "you", "today"};

        String[] stringArray = ArrayUtils.addAll(s1, s2);

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

        int [] salary1 = new int[]{1,2,3};
        int[] salary2 = new int[]{4,5,6};

        int[] intMergedArray = ArrayUtils.addAll(salary1, salary2);

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

    }
}

Output:

[hello, boss, welcome, nice, to, meet, you, today]
[1, 2, 3, 4, 5, 6]

5. Conclusion


In this post, you've seen how to merge or concatenate arrays in java.

All the programs are shown are over GitHub.

System.arraycopy()
Java Stream API
ArraysUtil.addAll() 

As usual all examples are over GitHub.

No comments:

Post a Comment

Please do not add any spam links in the comments section.