如何解决java 8 stream groupingBy进入自定义对象的集合
我的班级结构如下
public class Store {
private Long storeId;
private Long masterStoreId;
private String operatorIdentifier;
}
public class StoreInfo {
private String operatorIdentifier;
private Set<Long> slaveStoreIds;
public StoreInfo(String operatorIdentifier,Set<Long> slaveStoreIds) {
super();
this.operatorIdentifier = operatorIdentifier;
this.slaveStoreIds = slaveStoreIds;
}
}
我想将“ List
List<Store> stores;
Map<Long,Set<Long>> slaveStoresAgainstMasterStore = stores.stream().collect(Collectors
.groupingBy(Store::getMasterStoreId,Collectors.mapping(Store::getStoreId,Collectors.toSet())));
Map<Long,StoreInfo> storeInfoAgainstMasterStore = stores.stream()
.collect(
Collectors
.toMap(Store::getMasterStoreId,val -> new StoreInfo(val.getOperatorIdentifier(),slaveStoresAgainstMasterStore.get(val.getMasterStoreId())),(a1,a2) -> a1));
解决方法
由于masterStoreId
和operatorIdentifier
在组中相同(已在注释中确认),因此可以进行分组通过使用AbstractMap.SimpleEntry
创建它们对。然后使用Collectors.toMap
创建地图。
Map<Long,StoreInfo> storeInfoMap =
stores.stream()
.collect(Collectors.groupingBy(
e -> new AbstractMap.SimpleEntry<>(e.getMasterStoreId(),e.getOperatorIdentifier()),Collectors.mapping(Store::getStoreId,Collectors.toSet())))
.entrySet()
.stream()
.collect(Collectors.toMap(e -> e.getKey().getKey(),e -> new StoreInfo(e.getKey().getValue(),e.getValue())));
,
要完成实施,您正在尝试。您需要确保StoreInfo
中的合并功能,例如:
public StoreInfo(String operatorIdentifier,Long slaveStoreId) {
this.operatorIdentifier = operatorIdentifier;
this.slaveStoreIds = new HashSet<>();
this.slaveStoreIds.add(slaveStoreId);
}
public static StoreInfo mergeStoreInfo(StoreInfo storeInfo1,StoreInfo storeInfo2) {
Set<Long> slaveIds = storeInfo1.getSlaveStoreIds();
slaveIds.addAll(storeInfo2.getSlaveStoreIds());
return new StoreInfo(storeInfo1.getOperatorIdentifier(),slaveIds);
}
这将简化收集器的实现,并且您将相应地调用它们:
Map<Long,StoreInfo> storeInfoAgainstMasterStore = stores.stream()
.collect(Collectors.toMap(Store::getMasterStoreId,store -> new StoreInfo(store.getOperatorIdentifier(),store.getStoreId()),StoreInfo::mergeStoreInfo));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。