I am wondering why the Java Collection API does not contain convenient map methods for different types of collections. I would like to write something like:
List<Foo> list = ...; List<String> result = list.map(Foo::toString);
Instead, I need to create a stream, display and assemble, for example:
List<Foo> list = ...; List<String> result = list.stream().map(Foo::toString).collect(toList());
Wouldn't it be as simple as implementing this default method in the java.util.List interface? For instance.
default <R> List<R> map(Function<E, R> mapper){ return stream().map(mapper).collect(Collectors.toList()); }
At first glance, there seem to be other convenience methods. For instance:
list.stream().forEach(x -> {});
can be written as
list.forEach(x -> {});
However, the comparison is not so good. Iteratable.forEach is the default method on the top-level interface and does not require a return type. This does not create a stream under the hood, but uses the Iteratables properties to ... well ... iterate through all the elements.
So the question remains: Why not use the map method for each collection API? Maybe because it is not flexible enough, because you will need to choose the type of return?
I am sure that the developers thought about it and had their own reasons not to embed it. And I would like to understand why.
source share