Skip to content
Advertisement

Custom sorting by two parameters not working correctly

public List<List<Integer>> demo(int[][] buildings) {
    List<List<Integer>> tracker = new ArrayList<>();
    int pointer = 0;
    for (int i = 0; i < buildings.length; i++) {
        tracker.add(Arrays.asList(buildings[i][0], -buildings[i][2]));
        tracker.add(Arrays.asList(buildings[i][1], buildings[i][2]));
    }
    Collections.sort(tracker, (a, b) -> {
        if (a.get(0) != b.get(0)) {
            return a.get(0).compareTo(b.get(0));
        } else {
            return a.get(1).compareTo(b.get(1));
        }
    });
    return tracker;
}

When I input:

[[1,10001,10000],[2,10001,9999],[3,10001,9998]]

the output I get is:

[[1,-10000],[2,-9999],[3,-9998],[10001,10000],[10001,9999],[10001,9998]]

This is not the output that I expect, because my sorting rule is supposed to be when 10001 == 10001 then the ones with smaller second coordinates should be arranged at first.

Advertisement

Answer

I think the issue is Integer caching. For the low numbers, the Integer is cached so != works. For the large numbers, new Integers are used. Use Integer.equals to check for equality.

Change:

if(a.get(0) != b.get(0))

Into:

if( a.get(0).equals(b.get(0)) )

Otherwise you’re comparing the reference not the value.

Another way would be to use the helper methods of the Comparator class.

Comparator.<List<Integer>>comparing( list -> list.get(0) ).thenComparing(list-> list.get(1) );
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement