summary of point lambdafication survey
Henri Gerrits
henrigerrits at yahoo.com
Wed Sep 28 07:25:18 PDT 2011
>>>* Collections.toMap(keyGen)
>>>- for each element in a Collection, generate a key, store into a Map
>>>- could be a static utility method or an extension method
>>
>>This is interesting. It's sort-of halfway between two different ideas.
>>
>>One take would be for it to take a value-generating lambda (a Mapper) which
>>would be run over each element in a Set. The result would be a Map object whose
>>keys are the elements from the Collection and whose values are the results from
>>the Mapper.
>>
>>Another take is to generate keys from each element of a Collection; the
>>question then what to do in the case of duplicate keys. We'd want the resulting
>>Map to have multiple values for a single key. This could be expressed as a
>>(hypothetical) MultiMap, or as an ordinary Map whose values are Lists.
>
>... which turns it into groupBy.
I have a different interpretation of the "another take". If the semantics of toMap are defined such that the key generated from the Collection element should be unique, then toMap() would return a simple flat Map, while duplicate keys would be a violation of the semantics and therefore cause some RuntimeException.
The following example may illustrate this use case:
Collection<Customer> customers = datastore.getCustomers(...);
Map<String, Customer> customersByID = customers.toMap(c -> c.id());
Map<Long, Customer> customersByPK = customers.toMap(c -> c.pk());
where id() and pk() return String and long, respectively.
I would use such map conversions quite a lot, particularly for caches and the like.
Map implementations should also have conversion constructors, so that you can choose the exact Map implementation you need:
ConcurrentHashMap(Collection<V> values, Mapper<V, K> mapper);
To be used like so:
Map<String, Customer> = new ConcurrentHashMap<>(customers, c -> c.id());.
(Maybe a reversal of constructor arguments would be more intuitive, I'm not sure.)
Best regards,
Henri
More information about the lambda-dev
mailing list