Why don't Java collections provide a convenient map method?

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.

+5
source share
1 answer

Yes, this is intentional. Some of the reasons I heard about were discussed:

  • many times, these methods are combined together, in which case it is more efficient to collect only the explicit data structure at the end of the calculation.
  • control the absolute size of the interface; control the number of parameters displayed in autocomplete
  • avoid conflicts with external implementations of Collection that have already provided methods called map , etc.
  • create all smooth functions in one coherent API with special tuning methods, such as parallel() ; and that the API can now be developed separately from the collections that it created on
  • as you mentioned, let the user explicitly decide on the implementation of the return type - if you have an arbitrary Collection and named map on it, it can be either List or Set which silently deduplicates its output ?! that would be super confusing
+6
source

Source: https://habr.com/ru/post/1264704/


All Articles