Sorting Java Collections

By Harrison Brock / February 12, 2019

Sorting collections is a common task that Java developers deal with on a daily bases.  The Java Collections class provides us with two sort() methods to sort all collections that implement the List interface.

Sorting Primitive Types & Strings

In the example below, we will create a list with ten random integers and sort the list using the sort() method, which takes in a List of objects.

When we run the code above this is the output:

The numbers are now in sorted order. You can use this same method for sorting doubles, longs, and strings. To sort objects on a field like a name or age you have to use a comparator.

Sorting Object on a field Using a Comparator

For this example, we are going to sort a list of Students by their last name. To do this, we use the sort() which takes in a List of objects and a Comparator.

First, we need to create a class for students. You can have the code for the student class below.

In the code below we sort the students by their last name. We are comparing the last names on lines 23-26.

We can clean the code up a little by replacing the code on lines 21 – 27 above with this code:

This code is doing the same thing behind the scenes but, is much easier to read.

When we run the code above this is the output:


In this post, you learned how to sort Java Collections that are primitive types and classes that you have created yourself.

About the author

Harrison Brock