Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

java - Concatenating two int[]

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...