连接两个 int[] [英] Concatenating two int[]

查看:40
本文介绍了连接两个 int[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过 Streams 在 java 中连接两个 String[]Integer[] 有一些简单的解决方案.由于 int[] 经常使用.连接两个 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[]?

这是我的想法:

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]

它可以工作,但它实际上将 int[] 转换为 Integer[],然后将 Integer[] 转换回 int[] 再次.

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

推荐答案

您可以将 IntStream.concatArrays.stream 结合使用,无需任何自动装箱或拆箱.这是它的外观.

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();

请注意,Arrays.stream(c) 返回一个 IntStream,然后在收集到一个数组之前与另一个 IntStream 连接.

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

这是输出.

[1, 34, 3, 1, 5]

[1, 34, 3, 1, 5]

这篇关于连接两个 int[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆