Concatenating two int[]

徘徊边缘 提交于 2019-12-09 05:04: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.


回答1:


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]




回答2:


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

int[] m = IntStream.concat(IntStream.of(c), IntStream.of(d)).toArray();



回答3:


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++;
}


来源:https://stackoverflow.com/questions/54864223/concatenating-two-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!