How to collect with grouping by with reducing downstream?

Viewed 965

I have a problem with groupingBy collecting. In my case all elements in list have unique addressType value. I want to get a Map<String, Address> but have Map<String, Optional<Address>>

List<Address> list = ....
Map<String, Optional<Address>> collect = list.stream()
    .collect(Collectors.groupingBy(Address::getAddressType,
             Collectors.reducing((o, o2) -> o)));
1 Answers

Since all elements in list have unique addressType value, there's no reason to use Collectors.groupingBy in this case. Use Collectors.toMap instead:

Map<String, Address> collect = 
    list.stream()
        .collect(Collectors.toMap(Address::getAddressType,
                                  Function.identity()));
Related