0

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

1
  • 1
    Comparator.<Point>comparingInt(p -> p.x).thenComparingInt(p -> p.y). (Or comparingDouble, or whatever). Commented Sep 26, 2019 at 13:25

2 Answers 2

1

Use the shortest way possible, e.g. Comparator.comparing(Point::getX).thenComparing(Point::getY).

There's no reason to use the longer versions. They're less readable, and it's too easy to make mistakes. As an example, here's one possible implementation

(p1, p2) -> {
    if(p1.x == p2.x) {
        return p1.y.compareTo(p2.y);
    }
    return p1.x.compareTo(p2.x);
}

Takes a lot longer to understand what's happening there, doesn't it?

Sign up to request clarification or add additional context in comments.

Comments

0

Just use brackets to make a greater name space for lambda function to compare

Arrays.sort(points, (p1, p2) -> {
    int x1 = p1[0];
    int x2 = p2[0];
    int y1 = p1[1];
    int y2 = p2[1];
     // just for readability no need to make local variables
    if(x1 == x2){
      // compare y1 and y2 values here return 1 for greater 0 for equal -1 for less then
    }else{
    // x compare

    }



});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.