I'm wondering why the Java Collections API doesn't contain handy map
methods on the different collection types. I would like to write something like:
List<Foo> list = ...;
List<String> result = list.map(Foo::toString);
Instead I have to create a stream, map and collect, like this:
List<Foo> list = ...;
List<String> result = list.stream().map(Foo::toString).collect(toList());
Wouldn't it be as easy as implementing this default method in the java.util.List interface? E.g.
default <R> List<R> map(Function<E, R> mapper){
return stream().map(mapper).collect(Collectors.toList());
}
On first sight, it seems like other convenients methods are in place. For example:
list.stream().forEach(x -> {});
can be written as
list.forEach(x -> {});
However, the comparision is not that good. Iteratable.forEach is a default method on the top level interface and doesn't need to specify a return type. It's not creating a stream under the hood, but rather using Iteratables properties to... well... iterate all elements.
So the question remains: Why not have a map method on each and every Collections API interface? Maybe because it's not flexible enough because you would need to decide on a return type?
I'm sure the implementors thought about it and had their reasons to not put it in. And I would like to understand why.