Zip 2 Collections 基于 Java 中的值

Zip 2 Collections based on a value in Java

我有 2 Collection 的一些 objects AB 有一个字段 key。我想根据该字段压缩那些 2 collections 以获得具有相同 key.

的 objects A 和 B 的元组

发件人:

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

与您的解决方案差别不大,但 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());