-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 + ")";
        }
    }
1
  • 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. Commented Jun 3, 2021 at 7:20

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

4 Comments

You can also use list.sort(…) directly.
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?
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 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.
Yes, list.sort is just more readable I guess. Thanks for the detailed explanation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.