Transform a set into a map using the current lambda API
Sam Pullara
sam at sampullara.com
Tue Mar 26 13:16:09 PDT 2013
Also, you could use groupingBy, but it returns a list since it doesn't
know that your keys are unique:
Map<String, List<Property>> map =
properties.stream().collect(groupingBy(p -> p.name));
Sam
On Tue, Mar 26, 2013 at 1:12 PM, Sam Pullara <sam at sampullara.com> wrote:
> HashMap<String, Property> map =
> properties.stream().collect(HashMap<String, Property>::new, (m, p) ->
> m.put(p.name, p), Map::putAll);
>
> The convenience methods for toMap() collectors have the key/value reversed.
>
> Sam
>
> On Tue, Mar 26, 2013 at 11:18 AM, 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