3

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>
Naman
  • 27,789
  • 26
  • 218
  • 353
Ashishkumar Singh
  • 3,580
  • 1
  • 23
  • 41
  • 1
    Related/Possible duplicate of [How do I convert a Java 8 IntStream to a List?](https://stackoverflow.com/questions/23674624/how-do-i-convert-a-java-8-intstream-to-a-list) and/or [How to convert int array to Integer array in Java?](https://stackoverflow.com/questions/880581/how-to-convert-int-to-integer-in-java) – Naman Jan 11 '19 at 00:41

5 Answers5

5

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.

Community
  • 1
  • 1
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
4

box the stream:

Arrays.stream(arr2).boxed();
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • 3
    @AshishkumarSingh If you **really** insisted on starting with `Stream.of(arr2)` then you could do `Stream.of(arr2).flatMap(arr -> Arrays.stream(arr).boxed())`. But I don't know why you'd want to. – Michael Jan 11 '19 at 00:03
  • 2
    @Michael or `Stream.of(arr2).flatMapToInt(Arrays::stream).boxed()` – Holger Jan 11 '19 at 09:41
  • @Holger I was looking for what you commented. I know it doesn't make much sense to use when we have `Arrays.stream(arr2).boxed()`, but I just wanted to learn how can I achieve it if we have `Stream` – Ashishkumar Singh Jan 11 '19 at 16:05
3

You can use this:

Integer[] arr = Arrays.stream(arr2).boxed().toArray(Integer[]::new);
Gauravsa
  • 6,330
  • 2
  • 21
  • 30
1

You can create Stream from io.vavr with

Stream.ofAll(arr2)

but you want to use stream of integers you should use IntStream. You can create IntStream from array like this:

Arrays.stream(arr2)
jker
  • 465
  • 3
  • 13
1

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
nbrooks
  • 18,126
  • 5
  • 54
  • 66