I need to sort a list of Points. First I need to compare the x value, then if the x values are equal, the y value. So I thought I'd use the thenComparing method:
Comparator<Point> cmp = Comparator.comparingInt(p -> p.x).thenComparingInt(p -> p.y);
But I keep getting the message: Incompatible types: Comparator<Object> cannot be converted to Comparator<Point>.
There are other ways I can make this comparison, and it works, but I don't understand what I'm doing wrong here.
This code does work:
Comparator<Point> cmp = Comparator.<Point> comparingInt(p -> p.x)
.thenComparingInt(p -> p.y);
I only added <Point>
before comparingInt
, which explicitly declares the type of p
in the lambda. This is necessary, since Java cannot infer the type, due to the method chain.
See also Generic type inference not working with method chaining?
Here is another alternative:
Comparator<Point> cmp = Comparator.comparingDouble(Point::getX)
.thenComparingDouble(Point::getY);
Here, the type can be inferred without any problems. However, you need to use the double comparison, because getX
and getY
return double values. I personally prefer this approach.
Try changing:
Comparator<Point> cmp = Comparator.comparingInt(p -> p.x).thenComparingInt(p -> p.y);
to
Comparator<Point> cmp = Comparator.comparingInt((Point p) -> p.x).thenComparingInt((Point p) -> p.y);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With