Saturday, February 23, 2013

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 array into third array. But being a Java developer, I first looked in JDK to find any method which concatenate 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 method 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 package, which can concatenate two arrays in Java. It's always good to add Apache commons and Guava, as supporting library in Java project, they have lots of supporting classes, utility and method, which complements rich Java API. In this Java programming tutorial, we will see 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 than, 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 array in Java. Though we can also use ArrayUtils to combine object arrays, as it provides overloaded method for every type in Java, I have listed Guava example for sake of information. Open source libraries should be preferred, if you are doing real project and writing production code, because of testing advantage they provide. If you are combining arrays just as part of programming exercise or homework than 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 combine 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 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 uses Apache commons ArrayUtils, second array
 * join example uses Guava's ObjectArrays and last array concatenate 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 array contains same element, they will be repeated in combined array. You can concatenate or combine two arrays of different length as shown in second example, It's not necessary to be same length but they must be of same type, i.e. you can not combine String array to int array in Java. In order to use Apache commons and Google Guava you can include them as dependency in 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, example of combining or concatenating two int arrays as well as two String arrays. We have used library to do our job, which you should do if you are using it in your production code. If you are doing this as Java programming exercise, then you need to write method to combine two arrays by using standard JDK. You need to create new Array with length equal to sum of length of individual array and than you there use for loop or System.arrayCopy() method to copy individual array into combined array, as shown in our third array concatenation example in Java.

4 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.

Post a Comment