2017-08-30 93 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稍微乾淨。我想知道是否有一種方法不使用中間地圖,但我不這麼認爲 –