java - 如何检查两个流是否不相交?
问题描述
我想与流进行比较,并检查它们是否有 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
}
解决方案
在不单独收集两个流的情况下,您可以对多个值是否映射到任何键进行分组和识别。
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())
推荐阅读
- c++ - 使用 cmake 包含静态库
- angular - 如何在 Docker 映像创建过程中从 npm-install 过程中排除 @angular/cli?
- sql-server - 如何从 SQL Server 中检索已排序的分层数据
- java - 在 Eclipse Oxygen 上运行 GWT
- c# - 线程 0xc28 已退出,代码为 0
- node.js - express 验证器 useFirstErrorOnly 不起作用
- java - 单元测试中的 Spring Cloud Gateway 注入不起作用
- python - yt ProjectionPlot 的注解选项
- html - 带有标签的内联表单输入,输入居中
- python-3.x - 使用 os.scandir() 爬取一个非常大的目录并将文件发送到多处理队列发现