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.
IntStream.concatTransform 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With