user1798927 user1798927 - 1 month ago 6
Java Question

Java sort based on two columns - Without comparator

Here is the question:

Java sort based on two columns

But, can anyone explain how to do without using Comparator? In other words, How the comparator works internally for sorting multiple columns?

Answer

The sort method must have some way of finding out the relative order of pairs of rows. There are two supported ways of doing it using the normal sorts. Either use instances of a class that implements Comparable to represent rows, or use a Comparator.

If you don't want to do either of those, you would have to write your own, specialized, sort method. When it needs to compare two rows, it would look first at the higher priority column. If the rows differ in that column, that gives there order. If they are equal in that column, order them based on the second column.

That said, using a standard sort with either Comparable rows or a Comparator is much better than mixing up the sort logic and the comparison logic. Comparator is the more flexible way.