I want to sort an array of 2 dimensional arrays in Java according to some rules, let's say the distance from the origin. I saw several ways of doing it using Arrays.sort():
1) Arrays.sort(points, Comparator.comparing(p -> p[0]*p[0] + p[1]*p[1]));
2) Arrays.sort(points, (p1, p2) -> p1[0]*p1[0] + p1[1]*p1[1] - p2[0]*p2[0] - p2[1]*p2[1]);
3) Defining the class:
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);
}
}
An array pts of type Points is then created and Arrays.sort(pts) is used. My question is regarding 1) and 2): I see the difference between the but I do not understand when to use one and when to use the other and what exactly Comparator.comparing() is doing. Why is the first solution carrying the information just with one point while the second need two points?