Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list of points with Java [duplicate]

Tags:

java

sorting

I have a list of point objects, which I want to sort by a certain coordinate, say the x-values. Does Java provide any useful mechanisms or should I avail myself of one of the common sort algorithms?

like image 219
BarneyCrane Avatar asked Mar 03 '11 08:03

BarneyCrane


2 Answers

Yes create a custom Comparator , and use it to sort list of points

class Point{
    private int x;
    private int y;

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public Point() {
    }
}

List<Point> points = new ArrayList<Point>();
points.add(new Point(1, 2));
points.add(new Point(60, 50));
points.add(new Point(50, 3));
Collections.sort(points,new Comparator<Point>() {

public int compare(Point o1, Point o2) {
    return Integer.compare(o1.getX(), o2.getX());
}
});
like image 97
jmj Avatar answered Oct 17 '22 07:10

jmj


In Point class you should implement Comparable interface with generic type <Point> and use Collections.sort (java.util package) for sorting List<Point>

Assume:

class Point implements Comparable<Point>{
    int compareTo(Point other){ /* your logic */}
}

List<Point> list = new ArrayList<Point>();
/* adding points */
Collections.sort(list);
like image 20
Sergey Vedernikov Avatar answered Oct 17 '22 08:10

Sergey Vedernikov