【发布时间】:2021-01-08 16:38:50
【问题描述】:
我有以下类结构
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));
【问题讨论】:
-
您真的想要
Map<Long, StoreInfo>还是只想要List<StoreInfo>对您有用? .. 你需要弄清楚(a1, a2) -> a1做了什么并将其替换为你打算执行的操作。 -
@Naman 我不想要
List<StoreInfo>。我想在自定义 StoreInfo 对象中针对 masterStoreId 收集 storeId 列表。 -
masterStoreId 相同的 operatorIdentifier 相同?
-
@Rono 是的,masterStoreId 和 operatorIdentifier 是一样的
标签: java java-8 java-stream collectors