Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following class structure


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

}

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


See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
370 views
Welcome To Ask or Share your Answers For Others

1 Answer

As masterStoreId and operatorIdentifier are same same in group(comfirmed in comment) you can groupingBy both creating pair of them using AbstractMap.SimpleEntry. Then using Collectors.toMap create map.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...