2017-08-30 88 views
0

我有一些对象的s AB有一个字段key。我想压缩那些基于该字段的2个集合,使对象A和B的元组具有相同的key基于Java中的值的邮编2集合

来源:

Collection<A> a; 
Collection<B> b; 

要:

List<Pair<A, B>> ab; // where A and B have the same key field 

我在做什么,现在是手动构建Map<KeyType, Pair<A, B>>和创建从一个列表,但我相信有一个更好的方式来做到这一点。

编辑(解释我是如何创建地图):

Map<KeyType, Pair<A, B>> keyToAandB = new HashMap<>(); 

a.stream() 
    .forEach(aa -> keyToAandB.put(
     aa.getKey(), 
     Pair.of(aa, null))); 

b.stream() 
    .forEach(bb -> keyToAandB.put(
     bb.getKey(), 
     Pair.of(
      keyToAandB.get(bb.getKey()).getFirst(), 
      bb))); 
+0

使问题更清楚,你可以说明你是如何创建'Map > – nullpointer

回答

1

不是很从您的解决方案不同,但稍微干净IMO:

Map<KeyType, A> keyToA = a.stream() 
    .collect(Collectors.toMap(A::getKey, Function.identity())); 

List<Pair<A, B>> ab = b.stream() 
    .map(bb -> Pair.of(keyToA.get(bb.getKey()), bb)) 
    .collect(Collectors.toList()); 

如果你愿意承受二次性能,您可以使用嵌套流:

List<Pair<A, B>> ab = a.stream() 
    .map(aa -> Pair.of(aa, b.stream() 
     .filter(bb -> bb.getKey().equals(aa.getKey())) 
     .findAny() 
     .get())) // will throw exception if missing 
    .collect(Collectors.toList()); 
+0

yep稍微干净。我想知道是否有一种方法不使用中间地图,但我不这么认为 –