Java流:HashMap中没有重复项的对象列表
我正在尝试使用流将List
转换为Map
而不使用重复项,但我无法实现
我可以使用这样一个简单的循环:
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());
}
}
但当我尝试使用一条流时,我的大脑崩溃了
我必须说PropertyOwnerCommunityAddress
还包含两个对象:Community
和Address
,所有这一切的目标是为每个社区保存key:value
对中的地址,而不复制Community
对象
有人能帮我吗?谢谢!
# 1 楼答案
你必须使用
groupingBy
以获取Community
作为密钥mapping
获取Address
as列表