I'm trying to convert a List to Map without duplicates using a stream but I can't achieve it.
I can do it using a simple loop like this:
List<PropertyOwnerCommunityAddress> propertyOwnerCommunityAddresses = getPropertyOwnerAsList();
Map<Community, List<Address>> hashMap = new LinkedHashMap<>();
for (PropertyOwnerCommunityAddress poco : propertyOwnerCommunityAddresses) {
if (!hashMap.containsKey(poco.getCommunity())) {
List<Address> list = new ArrayList<>();
list.add(poco.getAddress());
hashMap.put(poco.getCommunity(), list);
} else {
hashMap.get(poco.getCommunity()).add(poco.getAddress());
}
}
but when I try to use a stream, my mind crash.
I have to say the PropertyOwnerCommunityAddress contains two object more: Community and Address and the goal of all of this is for each community save the addresses in a key:value pair without duplicate the Community object.
Anyone can help me? Thank you!
hashMap.computeIfAbsent(poco.getCommunity(), key -> new ArrayList<>()).add(poco.getAddress());