Transform a set into a map using the current lambda API

Brian Goetz brian.goetz at oracle.com
Tue Mar 26 18:01:34 PDT 2013


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.  



On Mar 26, 2013, at 1:37 PM, Ali Ebrahimi wrote:

> Hi,
> another solution with collect method:
> 
> names = properties.stream().collect(HashMap<String, Property>::new , ( m
> ,p)-> {m.put(p.name,p); } ,( m , n) -> {m.putAll(n); });
> 
> Ali Ebrahimi
> On Wed, Mar 27, 2013 at 12:43 AM, Ali Ebrahimi
> <ali.ebrahimi1781 at gmail.com>wrote:
> 
>> Hi,
>> this is an ugly solution:
>> 
>> Map<String, Property> names = properties.stream().reduce(new HashMap<>(),
>> ( u,  t) -> {
>>            u.put(t.name, t);
>>            return u;
>>        }, (m, n) -> {
>>            m.putAll(n);
>>            return m;
>>        });
>> 
>> 
>> 
>> Ali Ebrahimi
>> 
>> On Tue, Mar 26, 2013 at 10:48 PM, Marcos Antonio <
>> marcos_antonio_ps at hotmail.com> wrote:
>> 
>>> 
>>> Hello!
>>> 
>>> Suppose this simple POJO:
>>> 
>>> public class Property
>>> {
>>>    public String name;
>>>    public Object value;
>>>    @Override
>>>    public boolean equals(Object obj)
>>>    {
>>>        if (this == obj)
>>>        {
>>>            return true;
>>>        }
>>>        if (obj == null || getClass() != obj.getClass())
>>>        {
>>>            return false;
>>>        }
>>> 
>>>        Property another = (Property) obj;
>>>        return name.equals(another.name);
>>>    }
>>>    @Override
>>>    public int hashCode()
>>>    {
>>>        return name.hashCode();
>>>    }
>>> }
>>> 
>>> and a set of them:
>>> 
>>> Set<Property> properties = ...
>>> 
>>> using the current lambda API, what's the easiest way to transform this set
>>> in a map
>>> 
>>> Map<String, Property> names = ...
>>> 
>>> where the map key is the name field of the Property object and the map
>>> value
>>> is the Property object itself?
>>> 
>>> Thank you.
>>> 
>>> Marcos
>>> 
>>> 
>> 
> 



More information about the lambda-dev mailing list