Is there a way convert Stream<int[]>
to Stream<Integer>
int[] arr2 = new int[] { 54, 432, 53, 21, 43 };
// Below gives me Stream<int[]>
Stream.of(arr2); // I want to convert it to Stream<Integer>
Is there a way convert Stream<int[]>
to Stream<Integer>
int[] arr2 = new int[] { 54, 432, 53, 21, 43 };
// Below gives me Stream<int[]>
Stream.of(arr2); // I want to convert it to Stream<Integer>
You can use either Arrays.stream()
Arrays.stream(arr2).boxed(); // will return Stream<Integer>
Or IntStream.of
IntStream.of(arr2).boxed(); // will return Stream<Integer>
Stream<Integer> boxed()
Returns a Stream consisting of the elements of this stream, each boxed to an Integer.
This is an intermediate operation.
box the stream:
Arrays.stream(arr2).boxed();
You can use this:
Integer[] arr = Arrays.stream(arr2).boxed().toArray(Integer[]::new);
There is an issue in this case.
Let's look at an example. If you have an array of primitives and try to create a stream directly you will have a stream of one array object, like this:
// Arrays of primitives
int[] nums = {1, 2, 3, 4, 5};
Stream.of(nums); // One element int[] | Stream<int[]>
To solve this you can use:
Arrays.stream(nums).count(); // Five Elements
IntStream.of(nums).count(); // Five Elements