Skip to content

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:


the output I get is:


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.


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.


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


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) );