首页 > 解决方案 > 如何检查两个流是否不相交?

问题描述

我想与流进行比较,并检查它们是否有 1 个或多个共同元素(找到 1 就足以停止寻找更多)。我希望能够将其应用于包含自定义创建类的 Streams。

为了说明,假设我有一个看起来像这样的类:

public class Point {
    public final int row;
    public final int col;

    public Point(int row, int col) {
        this.row = row;
        this.col = col;
    }    

    @Override
    public boolean equals(Object obj) {
        if (obj == null) return false;
        if (obj.getClass() != this.getClass()) return false;
        final Point other = (Point) obj;
        return this.row == other.row && this.col == other.col;
    }

    @Override
    public int hashCode() {
        return Objects.hash(row, col); 
    }
}

然后我有两个可爱的流看起来像:

Stream<Point> streamA = Stream.of(new Point(2, 5), new Point(3, 1));
Stream<Point> streamB = Stream.of(new Point(7, 3), new Point(3, 1));

鉴于这些 Streams 有 1 个共同点(即Point(3, 1)),我希望最终结果为真。

所需的功能可以描绘为:

public static boolean haveSomethingInCommon(Stream<Point> a, Stream<Point> b){
    //Code that compares a and b and returns true if they have at least 1 element in common
}

标签: javajava-stream

解决方案


在不单独收集两个流的情况下,您可以对多个值是否映射到任何键进行分组和识别。

public static boolean haveSomethingInCommon(Stream<Coord> a, Stream<Coord> b) {
    return Stream.concat(a, b)
            .collect(Collectors.groupingBy(Function.identity()))
            .values().stream()
            .anyMatch(l -> l.size() > 1);
}

如果同一个流可以有两次或更多次相同的元素,您可以更改代码以使用 -

Stream.concat(a.distinct(), b.distinct())

推荐阅读