简体   繁体   English

在 Array.sort() 中实现 Java 比较器

[英]Implement Java Comparator in Array.sort()

Assume I have an array of two dimensional arrays which represent points I want to compare.假设我有一个二维 arrays 数组,它们代表我要比较的点。 For example I can compare the distance from the origin.例如,我可以比较与原点的距离。 What I can do is create a class Point :我能做的是创建一个 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) .并用所有点填充一个Point类型的数组,然后使用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, ie :现在,如果我需要先比较 x 坐标,如果比较没有差异,则需要 y 坐标,即:

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

Use the shortest way possible, eg Comparator.comparing(Point::getX).thenComparing(Point::getY) .使用尽可能最短的方式,例如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?需要更长的时间才能理解那里发生的事情,不是吗?

Just use brackets to make a greater name space for lambda function to compare只需使用括号为 lambda function 做一个更大的命名空间来比较

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

    }



});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM