在Java 8中将两个对象列表合并为Map中具有不同对象值的对象

时间:2018-08-20 13:02:26

标签: java lambda collections java-8 java-stream

我有两个相同类型“ 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. Map<String, List<Long>>创建aList,例如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);

4 个答案:

答案 0 :(得分:3)

如何?

    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

答案 1 :(得分:2)

如果您将吸气剂添加到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);
    }
}

您可以仅保留3行,同时保留您意图的语义:

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方法,因为这只会对存储桶造成潜在的冲突,实际上不会增加​​性能。

答案 2 :(得分:0)

您可以这样写:

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

答案 3 :(得分:0)

就像您说的那样,首先可以创建一个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())
    ));

也可以随意将第一部分提取到函数中以提高可读性。