Assume I have an array of two dimensional arrays which represent points I want to compare. For example I can compare the distance from the origin. What I can do is create a class Point:
class Point implements Comparable<Point>{
// class variables, constructor
public int compareTo(Point p) {
return (x*x + y*y).compareTo(p.x*p.x + p.y*p.y);
}
}
and fill up an array of type Point with all the points and then use Array.sort(pointsArray).
This can be also done on the following ways:
1) Arrays.sort(points, Comparator.comparing(p -> p[0]*p[0] + p[1]*p[1]));
or
2) Arrays.sort(points, (p1, p2) -> p1[0]*p1[0] + p1[1]*p1[1] - p2[0]*p2[0] - p2[1]*p2[1]);
without creating any new data type. The explanation can be found in this question.
Now, what if I would need to compare the x coordinate first and, if the comparison shows no difference, the y coordinate, i.e. :
class Point implements Comparable<Point>{
// class variables, constructor
public int compareTo(Point p) {
int cmp = x.compareTo(p.x);
if(cmp == 0) return y.compareTo(p.y);
return cmp;
}
}
How can this be translated in 1) and 2) ?
Comparator.<Point>comparingInt(p -> p.x).thenComparingInt(p -> p.y). (OrcomparingDouble, or whatever).