Using Java streams to merge a pair of `int` arrays [duplicate]

强颜欢笑 提交于 2020-05-27 11:52:39

问题


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

Arrays.toString( merged ): [10, 20, 30, 40, 50, 60, 70, 80]

➥ 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 = … ?

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.

I am aware of IntStream but cannot see how to use it for this purpose.


回答1:


IntStream.concat

Transform each array into an IntStream. Then call IntStream.concat to combine.

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

See this code run live at IdeOne.com.

Output:

[10, 20, 30, 40, 50, 60, 70, 80]

Tip: To sort the results, call .sorted() before the .toArray(). As seen running on IdeOne.com.




回答2:


You could use something like that if you want to work with merged:

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

int[] ints = Arrays.stream(merged).mapToInt(o -> Integer.parseInt(o.toString())).toArray();
System.out.println(Arrays.toString(ints));

Output:

[10, 20, 30, 40, 50, 60, 70, 80]



回答3:


You can use concat method of Stream to merge them and use boxed method of IntStream to convert it to Stream.

int[] firstArray = new int[]{10, 20, 30, 40};
int[] secondArray = new int[]{50, 60, 70, 80};
Object[] merged =
        Stream
              .concat(Arrays.stream(firstArray).boxed(), Arrays.stream(secondArray).boxed())
              .toArray();

System.out.println(Arrays.toString(merged)); // [10, 20, 30, 40, 50, 60, 70, 80]



回答4:


Here is one way, using Stream::flatMapToInt.

int[] a = { 10 , 20 , 30 , 40 };
int[] b = { 50 , 60 , 70 , 80 };
int[] merged = Stream.of(a,b).flatMapToInt(IntStream::of)
                .toArray();


来源:https://stackoverflow.com/questions/61297074/using-java-streams-to-merge-a-pair-of-int-arrays

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