Concatenating two int[]

  • A+

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 =[]::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.


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

int[] result = IntStream.concat(,; 

Note that 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]


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: