Java - 基于X和Y坐标对一组点进行排序

时间:2015-04-14 10:03:42

标签: java sorting point comparator

我有一个点对象列表,需要按X和Y坐标进行排序,但是当我将它们传递给比较器对象时,只有一个坐标被排序(第一个坐标被调用)。为什么会发生这种情况的任何想法?

static public List<Point> convertToThreeByThreeGrid(String points) {
    String[] ptsArray;
    List<Point> ptsList = new ArrayList<>();
    String stripString = points.replace("[", "").replace("]", "").replace("(", "").replace(")", "").replace(" ", ",").trim();
    ptsArray = stripString.split(",");

    for(int i = 0; i < ptsArray.length; i += 2) {
        int x = Integer.parseInt(ptsArray[i]);
        int y = Integer.parseInt(ptsArray[i + 1]);
        System.out.println("X: " + x);
        System.out.println("Y: " + y);
        ptsList.add(new Point(x, y));
    }

    Collections.sort(ptsList, new Comparator<Point>() {
        public int compare(Point a, Point b) {
            int result = Integer.compare((int) a.getX(), (int) b.getX());
            if (result == 0 ) {
                result = Integer.compare((int) a.getY(), (int) b.getY());
            }
            return result;
        }
    });

   // subtract each coordinate by smallest x and y coordinate values
    List<Point> convertedPtList = new ArrayList<>();
    int smallestX = (int) ptsList.get(0).getX();
    int smallestY = (int) ptsList.get(0).getY();
    for (int i = 1; i < ptsList.size(); i++) {
        int x = ((int) ptsList.get(i).getX() - smallestX);
        int y = ((int) ptsList.get(i).getY() - smallestY);
        convertedPtList.add(new Point(x, y));
    }
    return convertedPtList;

  }
}

输出:

[java.awt.Point [x = 10,y = 26],java.awt.Point [x = 10,y = 26],java.awt.Point [x = 10,y = 28],java .awt.Point [X = 12,Y = 26]]

[java.awt.Point [x = 13,y = 26],java.awt.Point [x = 13,y = 28],java.awt.Point [x = 13,y = 28],java .awt.Point [x = 14,y = 27],java.awt.Point [x = 14,y = 27],java.awt.Point [x = 15,y = 26],java.awt.Point [ x = 15,y = 28],java.awt.Point [x = 15,y = 28]]

[java.awt.Point [x = 16,y = 26],java.awt.Point [x = 16,y = 28],java.awt.Point [x = 16,y = 28],java .awt.Point [x = 18,y = 26],java.awt.Point [x = 18,y = 26],java.awt.Point [x = 18,y = 28]]

1 个答案:

答案 0 :(得分:2)

for(int i = 0; i < ptsArray.length; i += 2) {
    int x = Integer.parseInt(ptsArray[i]);
    int y = Integer.parseInt(ptsArray[i+1]);
    ptsList.add(new Point(x, y));
}

Collections.sort( ptsList, new Comparator<Point>() {
       public int compare(Point x1, Point x2) {
         int result = Double.compare(x1.getX(), x2.getX());
         if ( result == 0 ) {
           // both X are equal -> compare Y too
           result = Double.compare(x1.getY(), x2.getY());
         } 
         return result;
      }
    });

// ptsList is now sorted by both X and Y!

修改

要找到最低的X和最低的Y,你也可以选择经典的&#39;没有任何(双重)排序的方式:

int minX = Integer.MAX_VALUE;
int minY = Integer.MAX_VALUE;

for ( Point p : ptsList ) {

  final int x = (int)p.getX();
  final int y = (int)p.getY();

  if ( x < minX ) {
    minX = x;
  } 

  if ( y < minY ) {
    minY = y;
  }
}