Java Sort using Comparable or Comparator

In Java, it is straightforward to sort objects of the predefined class such as Integer, Double, Float and String. This is because these classes have been implemented the Comparable interface.  Comparable defines a natural ordering, as when you’re defining it, you specify which one is  considered “less than” or “greater than” the another.

How can you sort custom Objects? For example, suppose you have a list of objects of Student class, which has name, age, and score attributes. You may want to sort the students by their scores. Another example is to sort a list strings by their length. 

In order to sort a list of custom Objects, we can use the Java Comparable or Comparator interface.

Implement Comparable interface

In the following example, we define a Student class, and implement the Comparable interface such that it can be sorted by the students’ score.

The output:

before sort
[Student Info: <name = Lily,age=23,score=90.0>, Student Info: <name = david,age=30,score=93.0>, Student Info: <name = Mary,age=25,score=88.0>]
after sort
[Student Info: <name = Mary,age=25,score=88.0>, Student Info: <name = Lily,age=23,score=90.0>, Student Info: <name = david,age=30,score=93.0>]

Sort Java objects using Comparator

There are many cases you have no control of the objects to be sorted. For instance, if the student class is defined by somebody else, and you want to sort the students by their age information. In this case, you can use Comparator. The following example shows how to call the sort method of Java List by providing an custom Comparator. 

The output is:

after sort by age
[Student Info: <name = Lily,age=23,score=90.0>, Student Info: <name = Mary,age=25,score=88.0>, Student Info: <name = david,age=30,score=93.0>]

Sort Java Strings by length

Suppose you have a list of Strings, you want to sort them by their length. We can define a comparator to do this. See the following code:

The output:

without sort
[hello, Li, learn4master, lean java, I like java]
sort in nature order
[I like java, Li, hello, lean java, learn4master]
sort by length
[Li, hello, lean java, I like java, learn4master]