MikaelF MikaelF -4 years ago 103
Java Question

Why is there no Stream.flatMap(Collection) method?

Currently, to convert a

to a
, you have to use the following:

Stream<Foo> stream = list.stream().flatMap(fs -> fs.stream());
Stream<Foo> stream = list.stream().flatMap(Collection::stream);

I think this is exactly what the method references were designed for, and it does improve readability quite a bit. Now consider this:

Stream<Bar> stream = list.stream().flatMap(fs -> fs.getBarList().stream());

Having two chained method calls, no method reference is possible, and I've had this happen to me a few times. While it is not a big issue, it seems to drift away from the method-reference brevity.

Having worked with JavaFX 8 a bit, I noticed that a constant of their API's is the convenience methods. Java is a very verbose language, and it seemed to me that simple method overloads were a big selling point for JavaFX.

So my question is, I wonder why there is no convenience method
that could be called like:

Stream<Bar> stream = list.stream().flatMap(Foo::getBarList);

Is this an intentional omission by the folks at Oracle? Or could this cause any confusion?

Note: I'm aware of the "no-opinion-based-questions policy," and I'm not looking for opinions, I'm just wondering if there is a reason that such a method is not implemented.

Answer Source
  • Because Stream is already a pretty big interface and there's resistance to making it bigger.
  • Because there's also the workaround list.stream().map(Foo::getBarList).flatMap(List::stream).

You can also see the original discussion at http://mail.openjdk.java.net/pipermail/lambda-libs-spec-observers/2013-April/001690.html ; I'm not seeing that option specifically discussed; it may have been discarded already at that point?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download