java 8流groupingBy进入自定义对象的集合

2022-01-22 00:00:00 java-8 java java-stream collectors

我有以下类结构


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<Store"进入Map".是否可以在单个操作/迭代中这样做?

I want to collect the "List<Store" into a "Map<Long, StoreInfo>". Is it possible to do so in a single operation/iteration?

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));


推荐答案

为了完成实现,您正在尝试.您需要确保 StoreInfo 中的合并功能,例如:

To complete the implementation, you were attempting. You need to ensure merging capability within StoreInfo such as :

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);
}

这将简化收集器的实现,您可以相应地调用它们:

this would simplify the implementation of collector and you an invoke these correspondingly:

Map<Long, StoreInfo> storeInfoAgainstMasterStore = stores.stream()
        .collect(Collectors.toMap(Store::getMasterStoreId,
                store -> new StoreInfo(store.getOperatorIdentifier(), store.getStoreId()),
                StoreInfo::mergeStoreInfo));

相关文章