arqam
arqam

Reputation: 3789

Efficient way of sorting a List<Point> by X value

I am doing some sort operation and the data structure that I am using is a List<Point>.

Now this Point has two values x and y, and the values are given not in a sorted manner.

I have to sort this List<Point> in an efficient way according to the value of x, either increasing x or decreasing x.

One solution can be a brute force approach of parsing through each value and comparing that value to all the other to find the smallest in each iteration but that will be an inefficient approach.

What other solution can be used for this problem.

Edit : Point is from org.opencv.core package.

Upvotes: 3

Views: 3570

Answers (1)

Thomas Fritsch
Thomas Fritsch

Reputation: 10127

I assume you are talking about class java.awt.Point, thus having a getX() method.

Using Java 8 you can sort points by x:

List<Point> points = ...;
points.sort(Comparator.comparing(Point::getX));

In lower versions of Java, such as 7, you can implement the Comparator to achieve this:

List<Point> points = ...;
Collections.sort(points, new Comparator<Point>() {
    @Override
    public int compare(Point p1, Point p2) {
        return Double.compare(p1.getX(), p2.getX());
    }
});

Upvotes: 6

Related Questions