6

This question already has an answer here:

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.


  • Perhaps you need to cast it into a point by writing (Point). Not sure at all, though. - Gendarme

2 답변


11

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.


3

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


Linked


Related

Latest