Why is there no IntStream.flatMapToObj ()?

I am trying to do something like this:

Stream<Object> stream = IntStream.of(...) .flatMapToObj(i -> getStreamOfObjects(i)); 

Unfortunately, IntStream.flatMapToObj() does not exist, even in Java 9.

  • Why was this ruled out?
  • What is the recommended workaround?
+6
java java-8 java-stream
source share
3 answers

Why was this omitted?

The API provides reusable building blocks. The relevant building blocks here are IntStream , mapToObj , flatMap . From this, you can achieve what you want: point the map into the stream at the objects, and then get a flat map. Providing permutations of building blocks would be impractical and more difficult to expand.

What is the recommended workaround?

As outlined earlier, use the available building blocks ( mapToObj + flatMap ):

 Stream<Object> stream = IntStream.of(...) .mapToObj(i -> Stream.of(...)) .flatMap(...); 
+11
source share

Just write

  IntStream.of(...).mapToObj(i -> getStreamOfObjects(i)).flatMap(stream -> stream) 
+6
source share

Using a streaming stream will work if you don't mind the cost of boxing in each int value.

 Stream<Object> stream = IntStream.of(...).boxed().flatMap(i -> getStreamOfObjects(i)); 
+6
source share

All Articles