java - 如何编写比较多个参数的比较器?
问题描述
我正在尝试编写一个比较器来比较坐标类的两个对象。Coordinate 类非常简单:
public class Coordinate {
private int x, y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
现在我希望比较器比较坐标类的两个实例的 x 和 y 值。这是一个例子:
我有一个坐标 c1,它有 x = 42 和 y = 23。我的第二个坐标 c2 有 x = 23 和 y = 54。现在我把它们都放在一个 ArrayList 中,并且想要对列表进行排序。我想按如下方式排序:
具有最低 y 值的坐标始终排在第一位,当您有两个具有相同 y 值的坐标时,坐标排在第一位,它的 x 值较低。
例子:
c1 (y = 4, x = 5 ) < c2 (y = 4, x = 6) < c3 (y = 5, x = 2)
那么我该如何为此目的编写比较器呢?
非常感谢!
解决方案
Comparator<Coordinate> c = Comparator.comparingInt(Coordinate::getY)
.thenComparingInt(Coordinate::getX);
您可以通过thenComparing
和构建复合比较器thenComparingX
。
var list = List.of(
new Coordinate(6, 4),
new Coordinate(2, 5),
new Coordinate(5, 4)
);
list.sort(c);
System.out.println(list);
片段打印
[{y=4, x=5}, {y=4, x=6}, {y=5, x=2}]
推荐阅读
- java - 我可以将列表作为参数传递给 Scala/Java 中以这种方式定义的方法 detectFormatAutomatically(delimitersForDetection:Char*)
- python - 尝试在 Python 中构建一个简单的计算器无法在数学符号之间进行迭代
- google-cloud-firestore - Firestore 安全规则 - 通配符集合名称?
- javascript - 如何在下拉列表中获取除隐藏和提交按钮之外的所有表单字段
- groovy - Groovy AST 方法调用表达式的目标方法未设置
- sql-server - 根据该行中的值填充行
- javascript - 需要优雅的方式从 Javascript 中的 json 映射中提取值作为字符串
- javascript - 与在 Angular6 中将组件添加到另一个组件相关的问题
- jquery - 对 jquery 加载和直接链接到 html 页面使用相对路径
- ssl - 在 Java 中设置 TLS 扩展(例如trusted_ca_keys)