Java Stream: List of objects to HashMap without duplicates

As you can have multiple Addresses per Community you can't use the toMap() collector, but you need to use groupingBy():

Map<Community, List<Address>> map = propertyOwnerCommunityAddresses.stream()
    .collect(Collectors.groupingBy(
        PropertyOwnerCommunityAddress::getCommunity,
        Collectors.mapping(
            PropertyOwnerCommunityAddress::getAddress, 
            Collectors.toList())
        )
    );

Depending on your personal preference, this can look messy and maybe more complicated than the simple for-loop, which can also be optimized:

for(PropertyOwnerCommunityAddress poco : propertyOwnerCommunityAddresses) {
    hashMap.computeIfAbsent(poco.getCommunity(), c -> new ArrayList<>()).add(poco.getAddress());
}

Depending if you only want to have unique addresses you may want to use Set, so change the Collectors.toList() to Collectors.toSet() or when you stay with your for-loop change the definition of hashMap to Map<Community, Set<Address>> and in the loop exchange new ArrayList<>() with new HashSet<>()


You have to use

  • groupingBy to get the Community as key
  • mapping to get the Address as list
Map<Community, List<Address>>  hashMap = propertyOwnerCommunityAddresses.stream()
            .collect(Collectors.groupingBy(PropertyOwnerCommunityAddress::getCommunity,
                    Collectors.mapping(PropertyOwnerCommunityAddress::getAddress, Collectors.toList())));