Tutorial

How to Sort a List in Java

Published on August 3, 2022
Default avatar

By Pankaj

How to Sort a List in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Sometimes we have to sort a list in Java before processing its elements. In this tutorial, we will learn how to sort a list in the natural order. We will also learn how to use our own Comparator implementation to sort a list of objects. Java List is similar to arrays except that the length of the list is dynamic and it comes in Java Collection framework. Actually, List is an interface and most of the time we use one of its implementation like ArrayList or LinkedList etc.

Java Sort List

Here we will learn how to sort a list of Objects in Java. We can use Collections.sort() method to sort a list in the natural ascending order. All the elements in the list must implement Comparable interface, otherwise IllegalArgumentException is thrown. Let’s look at a quick example to sort a list of strings.

package com.journaldev.sort;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class JavaListSort {

    /**
     * This class shows how to sort ArrayList in java
     * @param args
     */
    public static void main(String[] args) {
        List<String> strList = new ArrayList<String>();
        strList.add("A");
        strList.add("C");
        strList.add("B");
        strList.add("Z");
        strList.add("E");
        //using Collections.sort() to sort ArrayList
        Collections.sort(strList);
        for(String str: strList) System.out.print(" "+str);
    }

}

As you can see that we are using Collections.sort() method to sort the list of Strings. The String class implements Comparable interface. Output:

Java Sort List
Java Sort List

Java Sort List of Objects

Let’s see another example where we will sort a list of custom objects. Note that the class must implement Comparable interface.

package com.journaldev.sort;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class JavaSortListObject {

	public static void main(String[] args) {
		List<Data> dl = new ArrayList<>();
		dl.add(new Data(2));
		dl.add(new Data(3));
		dl.add(new Data(1));
		System.out.println("Original List::"+dl);
		Collections.sort(dl);
		System.out.println("Naturally Sorted List::"+dl);

	}

}

class Data implements Comparable<Data> {

	private int id;

	public Data(int i) {
		this.id = i;
	}

	@Override
	public int compareTo(Data d) {
		return this.id - d.getId();
	}

	public int getId() {
		return id;
	}

	@Override
	public String toString() {
		return "Data{"+this.id+"}";
	}
}

Output:

Original List::[Data{2}, Data{3}, Data{1}]
Naturally Sorted List::[Data{1}, Data{2}, Data{3}]

Sort a List in Java using Comparator

Collections.sort() method is overloaded and we can also provide our own Comparator implementation for sorting rules. Since Comparator is a functional interface, we can use lambda expressions to write its implementation in a single line.

Collections.sort(dl, (d1, d2) -> {
	return d2.getId() - d1.getId();
});
System.out.println("Reverse Sorted List using Comparator::" + dl);

Output:

Java Sort List Objects Comparator
Java Sort List Objects - Comparator

Summary

Collections class sort() method is used to sort a list in Java. We can sort a list in natural ordering where the list elements must implement Comparable interface. We can also pass a Comparator implementation to define the sorting rules.

You can checkout more examples from our GitHub Repository.

Reference: API Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel