簡體   English   中英

將兩個對象列表合並到Map中,值與Java 8中的不同對象相同

[英]Merge two lists of objects into Map having value as different object in java 8

我有兩個相同類型“ MyInfoObject”的列表(例如A和B):

public class MyInfoObject {
  private Long id;
  private String signature;

  public MyInfoObject(Long id, String signature) {
      super();
      this.id = id;
      this.signature = signature;
  }
}

我想創建這兩個列表的Map,以使列表A的所有ID和具有相同簽名的列表B的所有ID創建一個類型為“ BucketOfAandB”的存儲桶:

public class BucketOfAandB {
  private List<Long> aIds ;
  private List<Long> bIds ;

  public BucketOfAandB(List<Long> aIds, List<Long> bIds) {
    super();
    this.aIds = aIds;
    this.bIds = bIds;
  }
 }

因此,我的輸出將是Map<String, BucketOfAandB> ,其中鍵是簽名

例如,我的輸入是:

    List<MyInfoObject> aList = new ArrayList<>();
    aList.add(new MyInfoObject(1l, "a"));
    aList.add(new MyInfoObject(2l, "d"));
    aList.add(new MyInfoObject(3l, "b"));
    aList.add(new MyInfoObject(4l, "a"));
    aList.add(new MyInfoObject(5l, "a"));
    aList.add(new MyInfoObject(6l, "c"));
    aList.add(new MyInfoObject(7l, "a"));
    aList.add(new MyInfoObject(8l, "c"));
    aList.add(new MyInfoObject(9l, "b"));
    aList.add(new MyInfoObject(10l, "d"));

    List<MyInfoObject> bList = new ArrayList<>();
    bList.add(new MyInfoObject(11l, "a"));
    bList.add(new MyInfoObject(21l, "e"));
    bList.add(new MyInfoObject(31l, "b"));
    bList.add(new MyInfoObject(41l, "a"));
    bList.add(new MyInfoObject(51l, "a"));
    bList.add(new MyInfoObject(61l, "c"));
    bList.add(new MyInfoObject(71l, "a"));
    bList.add(new MyInfoObject(81l, "c"));
    bList.add(new MyInfoObject(91l, "b"));
    bList.add(new MyInfoObject(101l, "e"));

在這種情況下,我的輸出將是:

{
    a= BucketOfAandB[aIds=[1, 4, 5, 7], bIds=[11, 41, 51, 71]],
    b= BucketOfAandB[aIds=[3, 9], bIds=[31, 91]],
    c= BucketOfAandB[aIds=[6, 8], bIds=[61, 81]],
    d= BucketOfAandB[aIds=[2, 10], bIds=null],
    e= BucketOfAandB[aIds=null, bIds=[21, 101]],
}

我想使用Java 8 Streams做到這一點。

我發現的一種方法是:

  1. aList創建Map<String, List<Long>> ,說aBuckets
  2. 迭代bList並通過以下方式創建resultant Map<String, BucketOfAandB>
    • 2a。 將具有相同簽名的aBuckets中的List設置為結果,將其從aBuckets刪除
    • 2b。 bList元素添加到所需的簽名存儲區
  3. 迭代aBuckets所有剩余元素,並將它們添加到resultant

我想知道一種使用Java 8 Streams實施此方法的更好方法。

提前致謝!

編輯:我嘗試使用流,但對實施不是很滿意。 以下是我的邏輯:

Map<String, BucketOfAandB> resultmap  = new HashMap<>();

    // get ids from aList grouped by signature
    Map<String, List<Long>> aBuckets = aList.stream().collect(Collectors.groupingBy(MyInfoObject::getSignature,
            Collectors.mapping(MyInfoObject::getId, Collectors.toList())));

    // iterate bList and add it to bucket of its signature
    bList.forEach(reviewInfo -> {
        BucketOfAandB bucket = resultmap.get(reviewInfo.getSignature());

        if(null ==  bucket) {
            bucket = new BucketOfAandB();
            resultmap.put(reviewInfo.getSignature(), bucket);

            List<Long> sourceReviewBucket =  aBuckets.remove(reviewInfo.getSignature());
            if(null !=sourceReviewBucket) {
                bucket.setaIds(sourceReviewBucket);
            }
        }
        bucket.addToB(reviewInfo.getId());
    });

    Map<String, BucketOfAandB> result = aBuckets.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, e -> new BucketOfAandB(e.getValue(), null)));

    resultmap.putAll(result);

這個怎么樣:

    Map<String, List<Long>> mapA = aList.stream()
            .collect(Collectors.groupingBy(
                    MyInfoObject::getSignature,
                    Collectors.mapping(MyInfoObject::getId, Collectors.toList())));

    Map<String, List<Long>> mapB = bList.stream()
            .collect(Collectors.groupingBy(
                    MyInfoObject::getSignature,
                    Collectors.mapping(MyInfoObject::getId, Collectors.toList())));

    Map<String, BucketOfAandB> overAll = new HashMap<>();

    Set<String> allKeys = new HashSet<>();
    allKeys.addAll(mapA.keySet());
    allKeys.addAll(mapB.keySet());

    allKeys.forEach(x -> overAll.put(x, new BucketOfAandB(mapA.get(x), mapB.get(x))));

但這假設listA中存在的每個鍵都將存在於listB

如果將getters添加到MyInfoObject ,並且讓BucketOfAandB惰性地初始化其列表(即,沒有構造函數),如下所示:

public class BucketOfAandB {
    private List<Long> aIds;
    private List<Long> bIds;
    public void addAId(Long id) {
        if (aIds == null) {
            aIds = new ArrayList<>();
        }
        aIds.add(id);
    }
    public void addBId(Long id) {
        if (bIds == null) {
            bIds = new ArrayList<>();
        }
        bIds.add(id);
    }
}

您只需三行就可以做到,同時保留您意圖的語義:

Map<String, BucketOfAandB> map = new HashMap<>();
aList.forEach(o -> map.computeIfAbsent(o.getSignature(), s -> new BucketOfAandB())
  .addAId(o.getId()));
bList.forEach(o -> map.computeIfAbsent(o.getSignature(), s -> new BucketOfAandB())
  .addBId(o.getId()));

如果您正在使用並行流,請synchronize add方法,因為這只是存儲桶上的潛在沖突,因此實際上不會增加​​性能損失。

你可以這樣寫:

Function<List<MyInfoObject>, Map<String, List<Long>>> toLongMap =
      list -> list.stream()
                  .collect(groupingBy(MyInfoObject::getSignature,
                                      mapping(MyInfoObject::getId, toList())));

Map<String, List<Long>> aMap = toLongMap.apply(aList);
Map<String, List<Long>> bMap = toLongMap.apply(bList);

Map<String, BucketOfAandB> finalMap = new HashMap<>();
aMap.forEach((sign, listA) -> {
    finalMap.put(sign, new BucketOfAandB(listA, bMap.get(sign)));
});
bMap.forEach((sign, listB) -> {
    finalMap.putIfAbsent(sign, new BucketOfAandB(null, listB));
});

如您所說,首先可以創建Map<String, List<Long>> ,然后構建Map<String, BucketOfAandB>

Map<String, List<Long>> idsBySignatureA = aList.stream()
    .collect(Collectors.groupingBy(
        MyInfoObject::getSignature,
        Collectors.mapping(
            MyInfoObject::getId,
            Collectors.toList())));

Map<String, List<Long>> idsBySignatureB = bList.stream()
    .collect(Collectors.groupingBy(
        MyInfoObject::getSignature,
        Collectors.mapping(
            MyInfoObject::getId,
            Collectors.toList())));

Map<String, List<BucketOfAandB>> result = Stream.concat(idsBySignatureA.entrySet().stream(), idsBySignatureB.entrySet().stream())
    .collect(Collectors.groupingBy(
        Map.Entry::getKey,
        Collectors.mapping(entry -> 
            new BucketOfAandB(
                idsBySignatureA.get(entry.getKey()),
                idsBySignatureB.get(entry.getKey())), 
            Collectors.toList())
    ));

也可以隨意將第一部分提取到函數中以提高可讀性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM