如何检查两个流是否不相交? [英] How to check if two streams are disjoint?
问题描述
我想与流进行比较,并检查它们是否具有1个或多个共同的元素(发现1足以停止寻找更多元素).我希望能够将其应用于包含自定义类的Streams.
I would like to compare to streams, and check if they have 1 or more elements in common (finding 1 is sufficient to stop looking for more). I want to be able to apply this to Streams containing a custom-created class.
为说明起见,假设我有一个看起来像这样的课程:
For illustration, let's say I have a class that looks like:
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);
}
}
然后我有两个看起来很可爱的流:
And then I have two lovely streams that look like:
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)
),所以我希望最终结果为真.
Given that these Streams have 1 Point in common (namely, Point(3, 1)
), I would want the final result to be true.
所需的功能可以如下图所示:
The desired functionality can be pictured as:
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
}
推荐答案
首先,您必须将Streams转换为Set或List才能避免出现著名的错误:
First of all you have to convert your Streams to a Set or List to not get the famous error:
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
流转换为Set并使用:
Or you can convert only the b
Stream to a Set and use:
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>
作为参数.
I would recommend to Set<Coord>
instead of Stream<Coord>
as param in your method.
public static boolean haveSomethingInCommon(Set<Coord> a, Set<Coord> b) {
return a.stream().anyMatch(b::contains);
}
这篇关于如何检查两个流是否不相交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!