Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't there IntStream.flatMapToObj()?

I'm trying to do something like this:

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

Unfortunately, IntStream.flatMapToObj() doesn't exist, even in Java 9.

  1. Why was it left out?
  2. What's a recommended workaround?
like image 891
shmosel Avatar asked Dec 23 '16 05:12

shmosel


1 Answers

Why was it was left out?

The API provides reusable building blocks. The relevant building blocks here are IntStream, mapToObj, flatMap. From these you can achieve what you want: map an in stream to objects, and then get a flat map. Providing permutations of building blocks would not be practical, and harder to extend.

What's a recommended workaround?

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

Stream<Object> stream = IntStream.of(...)
    .mapToObj(i -> Stream.of(...))
    .flatMap(...);
like image 118
janos Avatar answered Sep 26 '22 10:09

janos