Write a java program to sort an ArrayList of objects by field or property.

To understand the question first go through this example.

To do the sorting according to a property we will need to implement the Comparator or Comparable interface.

But first, let’s start by sorting simple wrapper class objects.

Now let’s try the same with the objects of custom class.

As you can see, the compiler gives an error stating that ‘the suitable method for sorting is not found’.

It is because we have not implemented the Comparable interface in the student class.

But why it worked for Integer wrapper class?

Because almost all wrapper classes such as Integer, Double, Float, String etc already have implemented the method of Comparable interface within them.

So let’s do the same for our custom Student class.

Sorting ArrayList using Comparable

Sorting ArrayList using Comparator

The Student class objects can be sorted by individual field or property using the java.util.Comparator interface.

Collections.sort() takes the second argument as the instance of the class which implen=ments Comparator interface.

By implementing Comparator interfece we need to override the compare() method which accepts two user-defined type arguments(in our case is Student) and return an integer by comparing the objects by its property.

Comment below if you have any doubts or suggestion.

Leave a Reply

8 + 13 =