How To Sort A List In Java - DigitalOcean

  • Blog
  • Docs
  • Get Support
  • Contact Sales
  • Tutorials
  • Questions
  • Product Docs
  • Cloud Chats
  • Search Community

Report this

What is the reason for this report?This undefined is spamThis undefined is offensiveThis undefined is off-topicThis undefined is otherSubmit

Table of contents

  1. Java Sort List
  2. Java Sort List of Objects
  3. Sort a List in Java using Comparator
  4. Summary
  1. Tutorials
  2. Java
  3. How to Sort a List in Java
TutorialHow to Sort a List in JavaPublished on August 3, 2022JavaPankaj Kumar

By Pankaj Kumar

How to Sort a List in JavaTable of contentsPopular topics

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 our products

About the author

Pankaj KumarPankaj KumarAuthorSee author profile

Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev

See author profileCategory:TutorialTags:JavaWhile 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.

Still looking for an answer?

Ask a questionSearch for more helpWas this helpful?YesNoComments(0)Follow-up questions(0)Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.

Deploy on DigitalOcean

Click below to sign up for DigitalOcean's virtual machines, Databases, and AIML products.Sign up

Popular Topics

  1. AI/ML
  2. Ubuntu
  3. Linux Basics
  4. JavaScript
  5. Python
  6. MySQL
  7. Docker
  8. Kubernetes
  9. All tutorials
  10. Talk to an expert

Featured tutorials

  1. SOLID Design Principles Explained: Building Better Software Architecture
  2. How To Remove Docker Images, Containers, and Volumes
  3. How to Create a MySQL User and Grant Privileges (Step-by-Step)
  • All tutorials
  • All topic tags
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

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

Sign Up

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Learn more

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Learn more

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

SubmitSubmit

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

View all products

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

Get started

*This promotional offer applies to new accounts only.

© 2025 DigitalOcean, LLC.Sitemap.

Tag » How To Sort A List Java