erickimme
erickimme

Reputation: 363

sorting for 2 arraylist that each of them represent x and y coordinate

I have 2 arraylists

xVal : [9 8 6 5 4 3 2 -10 ]
yVal : [3 6 5 7 9 1 8 10 ]

I want to sort xVal in ascending order and also have corresponding yVal to move as xVal is sorted.

So result would be

xVal : [-10 2 3 4 5 6 8 9 ]
yVal : [ 10 8 1 9 7 5 6 3 ]

Thank you for time to explain it

Upvotes: 0

Views: 374

Answers (1)

zappee
zappee

Reputation: 22716

I would like to suggest you to use a different data structure here. You can create an own data type (POJO) for the x/y coordinates and then you can sort the list in a "normal" Java way.

This is the POJO what you can use:

public class Coordinate {
    public int x;
    public int y;

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

    @Override
    public String toString() {
        return "[" + x + ", " + y + "] ";
    }
}

And the main program which initialzes the list, sorts the coordinades based on X coordinate and then shows the result:

public class SortDemo {
    public static void main(String[] args) {
        // init the list
        List<Coordinate> coordinates = new ArrayList<>();
        coordinates.add(new Coordinate(9, 3));
        coordinates.add(new Coordinate(8, 6));
        coordinates.add(new Coordinate(6, 5));
        coordinates.add(new Coordinate(5, 7));
        coordinates.add(new Coordinate(4, 9));
        coordinates.add(new Coordinate(3, 1));
        coordinates.add(new Coordinate(2, 8));
        coordinates.add(new Coordinate(-10, 10));

        // sort
        Collections.sort(coordinates, (coordinate1, coordinate2) -> coordinate1.x - coordinate2.x);

        // display the content of the sorted list
        System.out.println(coordinates);
    }
}

Result:

[-10, 10] , [2, 8] , [3, 1] , [4, 9] , [5, 7] , [6, 5] , [8, 6] , [9, 3]

EDIT

toString():

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

For example:

Coordinate coordinate = new Coordinate(-10, 10);
System.out.println(coordinate);

OR

Coordinate coordinate = new Coordinate(-10, 10);
System.out.println(coordinate.toString());

You can check it in DEBUG mode in your IDE.

Sort

The mentioned short form of collection sort is equivalent with this:

class MySort implements Comparator<Student> {
    public int compare(Coordinate coordinate1, Coordinate coordinate2) {
        return coordinate1.x - coordinate2.x;
    }
}

// how to use
Collections.sort(coordinates, new MySort());

API doc of compare()

Upvotes: 1

Related Questions