-1

I want to sort a List<Pair<Long, Long>> list = new ArrayList<Pair<Long, Long>>(); according to both the indexes, firstly according to first index and if first indexes are equal then according to second index using Java 8 lambda function.

I could easily sort only by first index as: Collections.sort(list,(o1, o2) -> o1.first < o2.first ? -1:0);

If I want to sort according to both the indexes Collections.sort(list,(o1, o2) -> o1.first < o2.first ? -1 : o1.first == o2.first ? (o1.second < o2.second ? -1 : 0) : 0); But I don't think its the right way to do it. Can someone please provide a better syntax?

Pair definition:

    class Pair<Type1, Type2> {
        Type1 first;
        Type2 second;

        Pair(Type1 f, Type2 s) {
            this.first = f;
            this.second = s;
        }

        public String toString() {
            return "(" + this.first + ", " + this.second + ")";
        }
    }
Yash Sharma
  • 169
  • 13
  • 2
    You can tell that a comparator is broken when you see that it sometimes returns a negative number but never a positive number. That obviously breaks the symmetry requirement. – Holger Jun 03 '21 at 07:20

1 Answers1

1

Use Collections.sort along with a comparator construction function like this:

Collections.sort(list, 
    Comparator.comparing((Pair<Long, Long> p) -> p.first)
        .thenComparing(p -> p.second));

Update

Alternatively, as suggested in the comment below you could use List.sort and it is a bit more succinct than the utility method used above.

list.sort(Comparator.comparing((Pair<Long, Long> p) -> p.first)
    .thenComparing(p -> p.second));
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
  • 2
    You can also use `list.sort(…)` directly. – Holger Jun 03 '21 at 07:21
  • Of course, good catch. Sometimes it's confusing when the library authors provide different approaches of doing the same thing. However the suggested approach is much more succinct and worth mentioning as an update. Would the implementation specific to `List` use some specific optimizations over the utility method `Collections.sort`? – Ravindra Ranwala Jun 03 '21 at 07:35
  • 2
    In case of the commonly used `ArrayList`, the `sort` method has been overridden to skip the copying step of the `default` method, however, since [Java 8, update 20](https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8032636) the `Collections.sort(…)` method just delegates to `list.sort(…)`, so you get the advantages of specialized implementations automatically. So, both will do the same, but `list.sort(…)` is just simpler. – Holger Jun 03 '21 at 07:41
  • Yes, list.sort is just more readable I guess. Thanks for the detailed explanation. – Ravindra Ranwala Jun 03 '21 at 07:46