Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4536

Concatenate Two Arrays in Java

$
0
0

1. Overview

In this tutorial, we're going to discuss how to concatenate two arrays in Java.

First, we'll implement our own methods with the standard Java API.

Then, we'll have a look at how to solve the problem using commonly used libraries.

2. Introduction to the Problem

Quick examples may explain the problem clearly.

Let's say, we have two arrays:

String[] strArray1 = {"element 1", "element 2", "element 3"};
String[] strArray2 = {"element 4", "element 5"};

Now, we want to join them and get a new array:

String[] expectedStringArray = {"element 1", "element 2", "element 3", "element 4", "element 5"}

Also, we don't want our method only to work with String arrays, so we'll look for a generic solution.

Moreover, we shouldn't forget the primitive array cases. It would be good if our solution works for primitive arrays, too:

int[] intArray1 = { 0, 1, 2, 3 };
int[] intArray2 = { 4, 5, 6, 7 };
int[] expectedIntArray = { 0, 1, 2, 3, 4, 5, 6, 7 };

In this tutorial, we'll address different approaches to solve the problem.

3. Using Java Collections

When we look at this problem, a quick solution may come up.

Well, Java doesn't provide a helper method to concatenate arrays. However, since Java 5, the Collections utility class has introduced an addAll(Collection<? super T> c, T… elements) method.

We can create a List object, then call this method twice to add the two arrays to the list. Finally, we convert the resulting List back to an array:

static <T> T[] concatWithCollection(T[] array1, T[] array2) {
    List<T> resultList = new ArrayList<>(array1.length + array2.length);
    Collections.addAll(resultList, array1);
    Collections.addAll(resultList, array2);
    @SuppressWarnings("unchecked")
    //the type cast is safe as the array1 has the type T[]
    T[] resultArray = (T[]) Array.newInstance(array1.getClass().getComponentType(), 0);
    return resultList.toArray(resultArray);
}

In the method above, we use Java reflection API to create a generic array instance: resultArray.

Let's write a test to verify if our method works:

@Test
public void givenTwoStringArrays_whenConcatWithList_thenGetExpectedResult() {
    String[] result = ArrayConcatUtil.concatWithCollection(strArray1, strArray2);
    assertThat(result).isEqualTo(expectedStringArray);
}

If we execute the test, it'll pass.

This approach is pretty straightforward. However, since the method accepts T[] arrays, it doesn't support concatenating primitive arrays.

Apart from that, it's inefficient as it creates an ArrayList object, and later we call the toArray() method to convert it back to an array. In this procedure, the Java List object adds unnecessary overhead.

Next, let's see if we can find a more efficient way to solve the problem.

4. Using the Array Copy Technique

Java doesn't offer an array concatenation method, but it provides two array copy methods: System.arraycopy() and Arrays.copyOf().

We can solve the problem using Java's array copy methods.

The idea is, we create a new array, say result, which has result.length = array1.length + array2.length, and copy each array's elements to the result array.

4.1. Non-Primitive Arrays

First, let's have a look at the method implementation:

static <T> T[] concatWithArrayCopy(T[] array1, T[] array2) {
    T[] result = Arrays.copyOf(array1, array1.length + array2.length);
    System.arraycopy(array2, 0, result, array1.length, array2.length);
    return result;
}

The method looks compact. Further, the whole method has created only one new array object: result.

Now, let's write a test method to check if it works as we expect:

@Test
public void givenTwoStringArrays_whenConcatWithCopy_thenGetExpectedResult() {
    String[] result = ArrayConcatUtil.concatWithArrayCopy(strArray1, strArray2);
    assertThat(result).isEqualTo(expectedStringArray);
}

The test will pass if we give it a run.

There is no unnecessary object creation. Thus, this method is more performant than the approach using Java Collections.

On the other hand, this generic method only accepts parameters with the T[] type. Therefore, we cannot pass primitive arrays to the method.

However, we can modify the method to make it support primitive arrays.

Next, let's take a closer look at how to add primitive array support.

4.2. Add Primitive Array Support

To make the method support primitive arrays, we need to change the parameters' type from T[] to T and do some type-safe checks.

First, let's take a look at the modified method:

static <T> T concatWithCopy2(T array1, T array2) {
    if (!array1.getClass().isArray() || !array2.getClass().isArray()) {
        throw new IllegalArgumentException("Only arrays are accepted.");
    }
    Class<?> compType1 = array1.getClass().getComponentType();
    Class<?> compType2 = array2.getClass().getComponentType();
    if (!compType1.equals(compType2)) {
        throw new IllegalArgumentException("Two arrays have different types.");
    }
    int len1 = Array.getLength(array1);
    int len2 = Array.getLength(array2);
    @SuppressWarnings("unchecked")
    //the cast is safe due to the previous checks
    T result = (T) Array.newInstance(compType1, len1 + len2);
    System.arraycopy(array1, 0, result, 0, len1);
    System.arraycopy(array2, 0, result, len1, len2);
    return result;
}

Obviously, the concatWithCopy2() method is longer than the original version. But it's not hard to understand. Now, let's quickly walk through it to understand how it works.

Since the method now allows parameters with the type T, we need to make sure both parameters are arrays:

if (!array1.getClass().isArray() || !array2.getClass().isArray()) {
    throw new IllegalArgumentException("Only arrays are accepted.");
}

It's still not safe enough if two parameters are arrays. For example, we don't want to concatenate an Integer[] array and a String[] array. So, we need to make sure the ComponentType of the two arrays are identical:

if (!compType1.equals(compType2)) {
    throw new IllegalArgumentException("Two arrays have different types.");
}

After the type-safe checks, we can create a generic array instance using the ConponentType object and copy parameter arrays to the result array. It's quite similar to the previous concatWithCopy() method.

4.3. Testing the concatWithCopy2() Method

Next, let's test if our new method works as we expected. First, we pass two non-array objects and see if the method raises the expected exception:

@Test
public void givenTwoStrings_whenConcatWithCopy2_thenGetException() {
    String exMsg = "Only arrays are accepted.";
    try {
        ArrayConcatUtil.concatWithCopy2("String Nr. 1", "String Nr. 2");
        fail(String.format("IllegalArgumentException with message:'%s' should be thrown. But it didn't", exMsg));
    } catch (IllegalArgumentException e) {
        assertThat(e).hasMessage(exMsg);
    }
}

In the test above, we pass two String objects to the method. If we execute the test, it passes. This means we've got the expected exception.

Finally, let's build a test to check if the new method can concatenate primitive arrays:

@Test
public void givenTwoArrays_whenConcatWithCopy2_thenGetExpectedResult() {
    String[] result = ArrayConcatUtil.concatWithCopy2(strArray1, strArray2);
    assertThat(result).isEqualTo(expectedStringArray);
    int[] intResult = ArrayConcatUtil.concatWithCopy2(intArray1, intArray2);
    assertThat(intResult).isEqualTo(expectedIntArray);
}

This time, we called the concatWithCopy2() method twice. First, we pass two String[] arrays. Then, we pass two int[] primitive arrays.

The test will pass if we run it. Now, we can say, the concatWithCopy2() method works as we expected.

5. Using Java Stream API

If the Java version we're working with is 8 or newer, the Stream API is available. We can also resolve the problem using the Stream API.

First, we can get a Stream from an array by the Arrays.stream() method. Also, the Stream class provides a static concat() method to concatenate two Stream objects.

Now, let's see how to concatenate two arrays with Stream.

5.1. Concatenating Non-Primitive Arrays

Building a generic solution using Java Streams is pretty simple:

static <T> T[] concatWithStream(T[] array1, T[] array2) {
    return Stream.concat(Arrays.stream(array1), Arrays.stream(array2))
      .toArray(size -> (T[]) Array.newInstance(array1.getClass().getComponentType(), size));
}

First, we convert two input arrays to Stream objects. Second, we concatenate the two Stream objects using the Stream.concat() method.

Finally, we return an array containing all elements in the concatenated Stream.

Next, let's build a simple test method to check if the solution works:

@Test
public void givenTwoStringArrays_whenConcatWithStream_thenGetExpectedResult() {
    String[] result = ArrayConcatUtil.concatWithStream(strArray1, strArray2);
    assertThat(result).isEqualTo(expectedStringArray);
}

The test will pass if we pass two String[] arrays.

Probably, we've noticed that our generic method accepts parameters in the T[] type. Therefore, it won't work for primitive arrays.

Next, let's see how to concatenate two primitive arrays using Java Streams.

5.2. Concatenating Primitive Arrays

The Stream API ships different Stream classes that can convert the Stream object to the corresponding primitive array, such as IntStream, LongStream, and DoubleStream.

However, only int, long, and double have their Stream types. That is to say, if the primitive arrays we want to concatenate have type int[], long[], or double[], we can pick the right Stream class and invoke the concat() method.

Let's see an example to concatenate two int[] arrays using IntStream:

static int[] concatIntArraysWithIntStream(int[] array1, int[] array2) {
    return IntStream.concat(Arrays.stream(array1), Arrays.stream(array2)).toArray();
}

As the method above shows, the Arrays.stream(int[]) method will return an IntStream object.

Also, the IntStream.toArray() method returns int[]. Therefore, we don't need to take care of the type conversions.

As usual, let's create a test to see if it works with our int[] input data:

@Test
public void givenTwoIntArrays_whenConcatWithIntStream_thenGetExpectedResult() {
    int[] intResult = ArrayConcatUtil.concatIntArraysWithIntStream(intArray1, intArray2);
    assertThat(intResult).isEqualTo(expectedIntArray);
}

If we run the test, it'll pass.

6. Using the Apache Commons Lang Library

The Apache Commons Lang library is widely used in Java applications in the real world.

It ships with an ArrayUtils class, which contains many handy array helper methods.

The ArrayUtils class provides a series of addAll() methods, which support concatenating both non-primitive and primitive arrays.

Let's verify it by a test method:

@Test
public void givenTwoArrays_whenConcatWithCommonsLang_thenGetExpectedResult() {
    String[] result = ArrayUtils.addAll(strArray1, strArray2);
    assertThat(result).isEqualTo(expectedStringArray);
    int[] intResult = ArrayUtils.addAll(intArray1, intArray2);
    assertThat(intResult).isEqualTo(expectedIntArray);
}

Internally, the ArrayUtils.addAll() methods use the performant System.arraycopy() method to do the array concatenation.

7. Using the Guava Library

Similar to the Apache Commons library, Guava is another library loved by many developers.

Guava provides convenient helper classes to do array concatenation as well.

If we want to concatenate non-primitive arrays, the ObjectArrays.concat() method is a good choice:

@Test
public void givenTwoStringArrays_whenConcatWithGuava_thenGetExpectedResult() {
    String[] result = ObjectArrays.concat(strArray1, strArray2, String.class);
    assertThat(result).isEqualTo(expectedStringArray);
}

Guava has offered primitive utilities for each primitive. All primitive utilities provide concat() method to concatenate the arrays with the corresponding types, for example:

  • int[] – Guava: Ints.concat(int[] … arrays)
  • long[] – Guava: Longs.concat(long[] … arrays)
  • byte[] – Guava: Bytes.concat(byte[] … arrays)
  • double[] – Guava: Doubles.concat(double[] … arrays)

We can just pick the right primitive utility class to concatenate primitive arrays.

Next, let's concatenate our two int[] arrays using the Ints.concat() method:

@Test
public void givenTwoIntArrays_whenConcatWithGuava_thenGetExpectedResult() {
    int[] intResult = Ints.concat(intArray1, intArray2);
    assertThat(intResult).isEqualTo(expectedIntArray);
}

Similarly, Guava internally uses System.arraycopy() in the above-mentioned methods to do the array concatenation to gain good performance.

8. Conclusion

In this article, we've addressed different approaches to concatenate two arrays in Java through examples.

As usual, the complete code samples that accompany this article are available over on GitHub.

The post Concatenate Two Arrays in Java first appeared on Baeldung.
       

Viewing all articles
Browse latest Browse all 4536

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>