Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 219
Basil Bourque Avatar asked Dec 01 '22 09:12

Basil Bourque


1 Answers

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.

like image 130
Denis Zavedeev Avatar answered Dec 03 '22 23:12

Denis Zavedeev