Sort a List in Java Example

Sort a List in Java Example

List being widely used in Data Structure, has its own importance. List is used to store elements with its own defined methods. Let’s see how we can sort data stored in List. To learn more about List click here.

Sort a List containing Integer

To sort an List, use Collections.sort() method.


Sort a List containing String

We can use Collections.sort() method just like above example to sort a List containing String.


Sort a List containing custom objects as element using comparable.

In this example we have created one custom class Emp with firstName, lastName and age as instance variable. Emp class implements Comparable interface and sort Emp objects based on age.

Emp bean class

Main method to sort a List


We have sorted the Array which contains custom object as elements using Comparable. In Emp class, we have used “age” as a parameter to sort the elements of the array. But, what if we want to sort the array using other parameters for example, based on “firstName”. So, by using Comparable we can only sort elements on one parameter. To sort objects on different parameter we should use Comparator interface. Here is example to sort an array using Comparator interface using “firstName” as sort criteria.

Sort a List containing custom objects as element using Comparator


To Sort an Array in java click here.
To Sort a Map/HashMap in java click here.


Leave a Reply

Your email address will not be published. Required fields are marked *