Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparator comparingInt [duplicate]

Tags:

java

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.

like image 202
fwend Avatar asked Mar 27 '16 23:03

fwend


2 Answers

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.

like image 77
Stefan Dollase Avatar answered Oct 01 '22 14:10

Stefan Dollase


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);
like image 35
Darshan Mehta Avatar answered Oct 01 '22 14:10

Darshan Mehta