繁体   English   中英

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

[英]How to check if two streams are disjoint?

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

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

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

首先,您必须将 Streams 转换为 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);
}

或者您可以仅将b Stream 转换为 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>作为参数。

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

有一个功能disjointCollections

public static boolean haveSomethingInCommon( Stream<Coord> a, Stream<Coord> b ) {
  return( ! Collections.disjoint( a.collect( toList() ), b.collect( toList() ) ) );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM