问题描述
此页面显示了如何将两者结合Integer
对象的数组转换为Object
对象的数组.
This page shows how to combine two arrays of Integer
objects into an array of Object
objects.
Integer[] firstArray = new Integer[] { 10 , 20 , 30 , 40 };
Integer[] secondArray = new Integer[] { 50 , 60 , 70 , 80 };
Object[] merged =
Stream
.of( firstArray , secondArray )
.flatMap( Stream :: of )
.toArray()
;
➥有没有一种方法可以使用Java流来连接一对原始int
值而不是对象的数组?
➥ Is there a way to use Java streams to concatenate a pair of arrays of primitive int
values rather than objects?
int[] a = { 10 , 20 , 30 , 40 };
int[] b = { 50 , 60 , 70 , 80 };
int[] merged = … ?
我意识到使用Java流可能不是最有效的方法.但是我对基元和Java流的相互作用感到好奇.
I realize using Java streams may not be the most efficient way to go. But I am curious about the interplay of primitives and Java streams.
我知道 IntStream
,但看不到如何将其用于此目的.
I am aware of IntStream
but cannot see how to use it for this purpose.
推荐答案
IntStream.concat
将每个数组转换为IntStream
.然后调用 IntStream.concat
进行组合.
IntStream.concat
Transform each array into an IntStream
. Then call IntStream.concat
to combine.
最后,通过调用 IntStream::toArray
.
Lastly, generate an array of int
by calling IntStream::toArray
.
int[] a = { 10 , 20 , 30 , 40 };
int[] b = { 50 , 60 , 70 , 80 };
int[] merged = IntStream.concat(IntStream.of(a), IntStream.of(b)).toArray();
System.out.println(Arrays.toString(merged));
请参见此在IdeOne.com上实时运行的代码.
输出:
[10, 20, 30, 40, 50, 60, 70, 80]
提示:要对结果进行排序,请调用 .sorted()
在.toArray()
之前.如在IdeOne.com上运行.
Tip: To sort the results, call .sorted()
before the .toArray()
. As seen running on IdeOne.com.
这篇关于使用Java流合并一对`int`数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!