Possible groupingBy simplification?
Brian Goetz
brian.goetz at oracle.com
Tue Apr 9 14:16:58 PDT 2013
Paul suggested the following possible simplification for groupingBy. It
is somewhat counterintuitive at first glance, in that it removes the
most commonly used form (!), but might make things easier to grasp in
the long run (aided by good docs.)
Recall we currently have four forms of groupingBy:
// classifier only -- maps keys to list of matching elements
Collector<T, Map<K, List<T>>>
groupingBy(Function<? super T, ? extends K> classifier)
// Like above, but with explicit map ctor
<T, K, M extends Map<K, List<T>>>
Collector<T, M>
groupingBy(Function<? super T, ? extends K> classifier,
Supplier<M> mapFactory)
// basic cascaded form
Collector<T, Map<K, D>>
groupingBy(Function<? super T, ? extends K> classifier,
Collector<T, D> downstream)
// cascaded form with explicit ctor
<T, K, D, M extends Map<K, D>>
Collector<T, M>
groupingBy(Function<? super T, ? extends K> classifier,
Supplier<M> mapFactory,
Collector<T, D> downstream)
Plus four corresponding forms for groupingByConcurrent.
The first form is likely to be the most common, as it is the traditional
"group by". It is equivalent to:
groupingBy(classifier, toList());
The proposal is: Drop the first two forms. Just as users can learn that
to collect elements into a list, you do:
collect(toList())
people can learn that to do the simple form of groupBy, you can do:
collect(groupingBy(f, toList());
Which also reads perfectly well.
By cutting the number of forms in half, it helps users to realize that
groupingBy does just one thing -- classifies elements by key, and
collects elements associated with that key. Obviously the docs for
groupingBy can show examples of the simple grouping as well as more
sophisticated groupings.
More information about the lambda-libs-spec-experts
mailing list