如何检查两个流是否不相交?

alt-f4

我想与流进行比较,并检查它们是否具有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));

鉴于这些流有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
}
YCF_L

首先,您必须将流转换为Set或List才能避免出现著名的错误:

java.lang.IllegalStateException: stream has already been operated upon or closed

然后您可以这样使用anyMatch

public static boolean haveSomethingInCommon(Stream<Coord> a, Stream<Coord> b) {
    Set<Coord> setA = a.collect(Collectors.toSet());
    Set<Coord> setB = b.collect(Collectors.toSet());

    return setA.stream().anyMatch(setB::contains);
}

或者,您可以仅将bStream转换为Set并使用:

public static boolean haveSomethingInCommon(Stream<Coord> a, Stream<Coord> b) {
    Set<Coord> setB = b.collect(Collectors.toSet());
    return a.anyMatch(setB::contains);
}

我建议在您的方法中Set<Coord>不要使用Stream<Coord>param。

public static boolean haveSomethingInCommon(Set<Coord> a, Set<Coord> b) {
    return a.stream().anyMatch(b::contains);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章