Creating an array from two

Asked

Viewed 73 times

4

I have the situation where I need to build in java a arrayC[] from a arrayA[4] and a arrayB[7], where the arrayC[] should present in order the arrayA[4] and then the arrayB[7]:

for example:

arrayA[4] = {A0; A1; A2; A3};
arrayB[7] = {B0; B1; B2; B3; B4; B5; B6};
arrayC[i] = {A0; A1; A2; A3; B0; B1; B2; B3; B4; B5; B6};

How can I do that?

2 answers

8


There are numerous ways to do this. One of the ways is this:

XXX[] arrayC = new XXX[arrayA.length + arrayB.length];
for (int i = 0; i < arrayA.length; i++) {
    arrayC[i] = arrayA[i];
}
for (int i = 0; i < arrayB.length; i++) {
    arrayC[i + arrayA.length] = arrayB[i];
}

In the above example, XXX[] is the type of the array. This can be int[], boolean[], String[], Object[], etc..

Another way:

XXX[] arrayC = new XXX[arrayA.length + arrayB.length];
System.arraycopy​(arrayA, 0, arrayC, 0, arrayA.length);
System.arraycopy​(arrayB, 0, arrayC, arrayA.length, arrayB.length);

A third way, if the base type of the array is not a primitive type:

List<XXX> lista = new ArrayList<>();
lista.addAll(Arrays.asList(arrayA));
lista.addAll(Arrays.asList(arrayB));
XXX[] arrayC = lista.toArray(new XXX[0]);

A fourth way, using Streams:

XXX[] arrayC = Stream.concat(Stream.of(arrayA), Stream.of(arrayB)).toArray(XXX[]::new);

See here all these ways working on ideone.

  • I know it’s not part of the doubt, but I would stream some way to do it short too?

  • 1

    @Articuno Feito. :)

  • @Victorstafusa was worth man! the first method was what I came closest to doing before asking here (:

  • @Lucasmonteiro I think the thanks went to Victor, he who made this great answer :)

4

In Java 8 on:

import java.util.*;
import java.util.stream.*;

public class HelloWorld{

    public static void main(String []args){
        int[] a = new int[] { 1, 2, 3 };
        int[] b = new int[] { 40, 50, 60 };

        int[] array =
            IntStream.concat(Arrays.stream(a), Arrays.stream(b))
                .toArray();

        System.out.println(Arrays.toString(array));
    }
}
  • 2

    Use System.out.println(Arrays.toString(array)); instead of for.

  • 1

    Thanks @Victorstafusa, corrected here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.