24

There are easy solutions for concatenating two String[] or Integer[] in java by Streams. Since int[] is frequently used. Is there any straightforward way for concatenating two int[]?

Here is my thought:

int[] c = {1, 34};
int[] d = {3, 1, 5};
Integer[] cc = IntStream.of(c).boxed().toArray(Integer[]::new);
Integer[] dd = Arrays.stream(d).boxed().toArray(Integer[]::new);
int[] m = Stream.concat(Stream.of(cc), Stream.of(dd)).mapToInt(Integer::intValue).toArray();
System.out.println(Arrays.toString(m));

>>
[1, 34, 3, 1, 5]

It works, but it actually converts int[] to Integer[], then converts Integer[] back to int[] again.

Naman
  • 27,789
  • 26
  • 218
  • 353
Simon Z.
  • 598
  • 5
  • 11
  • 2
    There are various solutions for concatenating arrays here: https://stackoverflow.com/questions/80476/how-can-i-concatenate-two-arrays-in-java though they are not specific to ints. – rghome Feb 25 '19 at 14:26

3 Answers3

28

You can use IntStream.concat in concert with Arrays.stream to get this thing done without any auto-boxing or unboxing. Here's how it looks.

int[] result = IntStream.concat(Arrays.stream(c), Arrays.stream(d)).toArray();

Note that Arrays.stream(c) returns an IntStream, which is then concatenated with the other IntStream before collected into an array.

Here's the output.

[1, 34, 3, 1, 5]

Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
20

You can simply concatenate primitive(int) streams using IntStream.concat as:

int[] m = IntStream.concat(IntStream.of(c), IntStream.of(d)).toArray();
Naman
  • 27,789
  • 26
  • 218
  • 353
  • 4
    Just reads better in my opinion, though notably, the `IntStream.of` under the hood makes use of the `Arrays.stream` itself. – Naman Feb 25 '19 at 10:59
2

Use for loops, to avoid using toArray().

int[] e = new int[c.length+d.length];
int eIndex = 0;
for (int index = 0; index < c.length; index++){
    e[eIndex] = c[index];
    eIndex++;
}
for (int index = 0; index < d.length; index++){
    e[eIndex] = d[index];
    eIndex++;
}
  • 6
    No need to implement such loops by hand. Just use `int[] e = Arrays.copyOf(c, c.length+d.length); System.arraycopy(d, 0, e, c.length, d.length);` and you’re done. – Holger Feb 26 '19 at 08:57