Wednesday, July 14, 2021

2 Ways to Combine Arrays in Java – Integer, String Array Copy Example

There are multiple ways to combine or join two arrays in Java, both for primitive like int array and Object e.g. String array. You can even write your own combine() method which can use System.arrayCopy() to copy both those arrays into the third array. But being a Java developer, I first looked in JDK to find any method which concatenates two arrays in Java. I looked at java.util.Arrays class, which I have used earlier to compare two arrays and print arrays in Java, but didn't find a direct way to combine two arrays. Then I looked into Apache Commons, ArrayUtils class, and bingo, it has several overloaded methods to combine int, long, float, double, or any Object array.


Later I also found that Guava, earlier known as Google collections also has a class ObjectArrays in com.google.common.collect the package, which can concatenate two arrays in Java. 

It's always good to add Apache commons and Guava, as supporting libraries in the Java project, they have lots of supporting classes, utility, and methods, which complements rich Java API. 

In this Java programming tutorial, we will see an example of these 2 ways to combine, join or concatenate two arrays in Java and will write a method in core Java to concatenate two int arrays in Java.

In this Java example, we will first combine two int arrays and then, two String arrays. We will use Apache commons ArrayUtils.addAll() method to combine two integer arrays in Java and Google's Guava library to join two String arrays in Java. 

Though we can also use ArrayUtils to combine object arrays, as it provides an overloaded method for every type in Java, I have listed Guava's example for the sake of information. Open-source libraries should be preferred, if you are doing a real project and writing production code, because of the testing advantage they provide. 

If you are combining arrays just as part of a programming exercise or homework then you better try to write a method yourself, to join two arrays



How to combine Array in Java - Example

How to combine array in Java - String and Integer arrray exampleHere is complete code example of combining two arrays in Java. You can write this combined method for any Java data type or object, I have used integer arrays for simplicity. This is also a good opportunity to learn, how to use System.arrayCopy() method  in Java, which is the best way to copy one array to another in Java.

import com.google.common.collect.ObjectArrays;
import java.util.Arrays;
import org.apache.commons.lang.ArrayUtils;

/**
 * Java program to combine two arrays in Java. In this Java example
 * first we have concatenated two int arrays and later two String arrays.
 * First array combine examples use Apache commons ArrayUtils, second array
 * join example uses Guava's ObjectArrays and the last array concatenates example uses JDK.
 *
 * @author Javin Paul
 */
public class CombineArrayJava {

    public static void main(String args[]) {
      
        int [] first = {1,2,3, 4};
        int [] second = {5,6,7,8};
      
        // combine two arrays in Java using Apache commons ArrayUtils
        int [] combined = ArrayUtils.addAll(first, second);
     
        System.out.println("First array : " + Arrays.toString(first));
        System.out.println("Second array : " + Arrays.toString(second));
        System.out.println("Combined array : " + Arrays.toString(combined));

    
        String [] one = {"a", "b", "c"};
        String [] two = {"d", "e"};
      
        //joining array in Java using Guava library
        String [] joined = ObjectArrays.concat(one, two, String.class);
        System.out.println("Joined array : " + Arrays.toString(joined));
      
        //JDK way to combine two array in Java
        int[] array1 = {101,102,103,104};
        int[] array2 = {105,106,107,108};
        int[] concatenate = combine(array1, array2);
        System.out.println("concatenated array : " + Arrays.toString(concatenate));
      
    }
  
 
    public static int[] combine(int[] a, int[] b){
        int length = a.length + b.length;
        int[] result = new int[length];
        System.arraycopy(a, 0, result, 0, a.length);
        System.arraycopy(b, 0, result, a.length, b.length);
        return result;
    }
  
}

Output:
First array : [1, 2, 3, 4]
Second array : [5, 6, 7, 8]
Combined array : [1, 2, 3, 4, 5, 6, 7, 8]
Joined array : [a, b, c, d, e]
concatenated array : [101, 102, 103, 104, 105, 106, 107, 108]

Just keep in mind that, here we are combining two arrays, we are not merging arrays i.e. if both arrays contains the same element, they will be repeated in the combined array.

You can concatenate or combine two arrays of different lengths as shown in the second example, It's not necessary to be the same length but they must be of the same type, i.e. you can not combine the String array to int array in Java. 

In order to use Apache commons and Google Guava, you can include them as dependencies in the Maven project or you can simply add their respective JAR into classpath to compile this Java program.

That's all on How to combine two arrays in Java. We have seen, an example of combining or concatenating two int arrays as well as two String arrays. We have used a library to do our job, which you should do if you are using it in your production code. If you are doing this as a Java programming exercise, then you need to write a method to combine two arrays by using standard JDK. 

You need to create a new Array with a length equal to the sum of the length of the individual array and then you there use for loop or System.arrayCopy() method to copy individual array into a combined array, as shown in our third array concatenation example in Java.



Related Data Structure and Algorithm Interview Questions from Javarevisited Blog
  • Difference between array and linked list data structure? (answer)
  • Difference between a binary tree and binary search tree? (answer)
  • How to reverse a linked list in Java using iteration and recursion? (solution)
  • How to reverse an array in place in Java? (solution)
  • How to find all permutations of a String in Java? (solution)
  • How to reverse a String in place in Java? (solution)
  • How to remove duplicate elements from an array without using Collections? (solution)
  • Top 5 Books on Data Structure and Algorithms for Java Developers (books)
  • Top 5 books on Programming/Coding Interviews (list)

6 comments :

SARAL SAXENA said...

Hi Javin,

Great Article, one thing I would like to add is ..
If I want to copy a large array of integer values say form array a to array b than..

1) one way is
int[] a = new int[]{1,2,3,4,5};
int[] b = new int[5];
System.arraycopy( a, 0, b, 0, a.length );

2) other way is ..
int[] a = new int[]{1,2,3,4,5};
int[] b = (int[])a.clone();

3) and the third way could even be..
int[] b = Arrays.copyOf(a, a.length);

as we know there is a utility class Arrays which consists of several methods..be aware that Arrays.copyOf() was added later to the API

At last i only want to say that System.arraycopy is better way and thr reason for that is Its implemented through native code so it's more efficient,System.arraycopy is native implementation and efficient than cloning. It could copy array in single memorycopy

Javin @ xml interview questions said...

Hi Saral, great commena. Yes, you are correct, System.arraycopy() is the fastest way to copy array in Java and should always be preferred, most utility classes use that.

Prashant k said...

package com.pra.sss;
/*
* Vector v1 and V2 contain some common objects
* Create vector V3 which will contain all V1 and V2
* and common objects only once
* without using colletion framework functions
*/
import java.util.Vector;

public class VectorTest {
public static void main(String[] args) {
Vector v1 = new Vector();
Vector v2 = new Vector();
Vector v3 = new Vector();
/*Vector v1*/
v1.add("A");
v1.add("B");
v1.add("C");
v1.add("D");
/*Vector v2*/
v2.add("W");
v2.add("B");
v2.add("C");
v2.add("Z");

System.out.println("V1"+v1);
System.out.println("V2"+v2);

for(String ss : v1) {
v3.add(ss);
}

for (int i = 0; i < v1.size(); i++) {
for (int j = i; j < v2.size(); j++) {
if(v1.get(i).equals(v2.get(j))) {
break;
}
else{
v3.add(v2.get(j));
break;
}
}
}
System.out.println("v3:"+v3);
}
}

/*
output
V1[A, B, C, D]
V2[W, B, C, Z]
v3:[A, B, C, D, W, Z]
*/

Anonymous said...

What are some practical scenario when you need to concatenate two arrays or merge them? apart from interviews I have yet to see a good example, when you need to merge array in Java.

Fells said...

How do i get the ObjectArrays.concat to work ? Mine keeps saying that it cannot find the Symbol. I tried import com.google.common.collect.ObjectArrays but im not being able

javin paul said...

Hello Fells, can you share your code, I will try to run on my side?

Post a Comment