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.
The Map interface provides 3 views of key-value pairs which are: key set view. value set view. entry set view.
If you need fast access to elements using index, ArrayList should be choice. If you need fast access to elements using a key, use HashMap. If you need fast add and removal of elements, use LinkedList (but it has a very poor seeking performance).
Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.
Yes, this is deliberate. Some reasons I've heard discussed:
Collection
that already provided methods named map
, etc.parallel()
; and that API can now be evolved separately from the collections it's built onCollection
and called map
on it, it could either be a List
, or a Set
that silently deduplicates its output?! that'd be super confusing If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With