Transform a set into a map using the current lambda API
Brian Goetz
brian.goetz at oracle.com
Wed Mar 27 08:01:02 PDT 2013
Does
properties.stream().collect(HashMap::new, (m,p) -> m.put(p.name, p), Map::putAll);
seem so verbose or obscure?
Not averse to a canned Collector for it. Hard part is the right name. (Cue bikeshed frenzy.)
On Mar 27, 2013, at 7:57 AM, Michael Nascimento wrote:
> On Tue, Mar 26, 2013 at 10:01 PM, Brian Goetz <brian.goetz at oracle.com> wrote:
>> You should not need the explicit types on HashMap::new. You can use Map::putAll instead of (m,n) -> m.putAll(n). So this becomes:
>>
>> properties.stream().collect(HashMap::new, (m,p) -> m.put(p.name, p), Map::putAll);
>>
>> You could also package these lambdas into a Collector, whose factory method takes the V->K function, so you could write:
>>
>> properties.stream().collect(toBackwardsMap(Property::getName)));
>>
>>
>> This problem is basically the backwards version of what is implemented by Collectors.toMap.
>
> I am afraid this will be one of the most common usage patterns in Java
> EE applications. It is very common to index objects by their primary
> keys or unique keys. You need this for parsing a file, for SQL
> optimization, grouping, etc. Many view technologies (JSF for instance)
> require objects to be "serialized" into a view acceptable form as
> well, so you have to resort to this. There is the
> reduce/groupingBy/throwingMerger alternative as well, but I guess this
> is the main "pattern" missing in Collectors for these applications.
>
> Regards,
> Michael
More information about the lambda-dev
mailing list