Sorting a list of points with Java [duplicate]
Asked Answered
W

4

7

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?

Westbound answered 3/3, 2011 at 8:3 Comment(0)
A
21

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());
}
});
Azriel answered 3/3, 2011 at 8:4 Comment(0)
A
5

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);
Armindaarming answered 3/3, 2011 at 8:5 Comment(0)
B
1

You should either make your point class to implement Comparable interface or provide sort() method with your own Comparator object, which tells sort() how to order your objects. There a lot of examples around here.

Becalmed answered 3/3, 2011 at 8:8 Comment(0)
S
1

You can use something like a Bean Comparator so you don't have to keep creating custom Comparators.

Southing answered 3/3, 2011 at 16:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.