-2

I need to order an ArrayList of Points in the page line order. Assume these points as minX and minY of Rectangle of text.

Say like I have points like below

Point(100,10), Point(110, 20), Point(125, 5), Point(130, 10)

The Sorted order should be aligned as page line items

i.e Point(125, 5), Point(100,10), Point(130, 10), Point(110, 20)

I was trying to sort the Points by Y coordinate first and then by X coordinate

public int compare(final Point a, final Point b) {
    if (a.y() < b.y()) {
        return -1;
    }else if (a.y() > b.y()) {
        return 1;
    }else {
        return 0;
    }
}

public int compare(final Point a, final Point b) {
    if (a.x() < b.x()) {
        return -1;
    }else if (a.x() > b.x()) {
        return 1;
    }else {
        return 0;
    }
}

enter image description here

Below is the order I am getting now

Line = 0.00 2450 00 SewiceTax @14 on are, Sub Total Two Thousand Four Hundred Fifty Only INR

Line = Swachh Bharat Cass @ O 50 42':

Line = Knshu Kaiyan Cass @ 0‘50 “5

Line = Less Advance Paid

Line = 2450 GD Balance Payable

Expected was

Line = Sub Total Two Thousand Four Hundred Fifty Only 0.00 2450 00INR SewiceTax @14 on are,

Ranju
  • 147
  • 2
  • 4
  • 10

2 Answers2

0

Use Comparator, and override compare() according to your usecase. These links will help you

How to sort ArrayList using Comparator?

How to use Comparator in Java to sort

bibbsey
  • 969
  • 2
  • 9
  • 14
0

This should work for you. Sort the Points by Y coordinate first and then by X coordinate.

Point p1 = new Point(12,  15);
Point p2 = new Point(13,  12);
Point p3 = new Point(14,  15);

List<Point> list = new ArrayList<>();
list.add(p1);
list.add(p2);
list.add(p3);

Comparator<Point> comp = new Comparator<Point>() {
    @Override
    public int compare(Point p1, Point p2) {
        return p2.y  == p1.y ? p2.x -p1.x : p2.y-p1.y;
    }
};
list.sort(comp);
Burak
  • 2,251
  • 1
  • 16
  • 33
nagendra547
  • 5,672
  • 3
  • 29
  • 43
  • 1
    looks promising.. I'll check and let you know. may be the order I have to change.. np man I'll up vote. there are some people just for this... – Ranju Aug 23 '17 at 08:57