Wednesday, 22 January 2014

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.


No comments:

Post a Comment