HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Collections Framework / Java ArrayList / ArrayList sort() – Sort list of objects by field

ArrayList sort() – Sort list of objects by field

ArrayList sort() method sorts the list according to the order induced by the specified Comparator instance. All elements in the list must must be mutually comparable.

1. ArrayList sort() method

The sort() method accepts an instance of Comparator implementing class which must be able to compare the elements contained in the arraylist.

Internally, the sort() method uses Arrays.sort() method to compare and sort the elements in the list.

public void sort(Comparator<? super E> c) 
{
    final int expectedModCount = modCount;

    Arrays.sort((E[]) elementData, 0, size, c);

    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
    modCount++;
}

Method parameter – Comparator implemetation.
Method returns – void.
Method throws – ConcurrentModificationException if list is modified while sort() method is not finished.

2. ArrayList sort() – Sort list of objects by field

Comparators are most useful when we want to sort a given list of objects – but not in natural order. For example, a list of employees should be sorted on their employee id, naturally.

Another usecase of comparator is that when objects in the list are not implementing Comparable interface. Also, we may want to sort objects list in different ways in different scenarios.

For example, an employee list can be sorted by their name, age or their any other such field. Comparator are best fit in these types of requirements.

2.1. Employee Class

Let’s create a simple employee class with only 3 fields to make this example cleaner.

import java.time.LocalDate;

public class Employee {

    private Long id;
    private String name;
    private LocalDate dob;

    public Employee(Long id, String name, LocalDate dob) {
        super();
        this.id = id;
        this.name = name;
        this.dob = dob;
    }

    //Getters and Setters

    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", dob=" + dob + "]";
    }
}

2.2. Comparator classes to enable sorting on different fields

Comparator to sort the employee list by name alphabetically.

import java.util.Comparator;

public class NameSorter implements Comparator<Employee> 
{
    @Override
    public int compare(Employee o1, Employee o2) {
        return o2.getName().compareToIgnoreCase(o1.getName());
    }
}

Comparator to sort the employee list by age in ascending order.

import java.util.Comparator;

public class AgeSorter implements Comparator<Employee> 
{
    @Override
    public int compare(Employee o1, Employee o2) {
        return o2.getDob().compareTo(o1.getDob());
    }
}

Comparator to sort the employee list by id.

import java.util.Comparator;

public class IdSorter implements Comparator<Employee> 
{
    @Override
    public int compare(Employee o1, Employee o2) {
        return o2.getId().compareTo(o1.getId());
    }
}

2.3. ArrayList sort() example

Now let’s use the comparator classes to sort a list of employees by name.

import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList;

public class ArrayListExample 
{
    public static void main(String[] args) throws CloneNotSupportedException 
    {
        ArrayList<Employee> employees = new ArrayList<>();
        
        employees.add(new Employee(1l, "Alex", LocalDate.of(2018, Month.APRIL, 21)));
        employees.add(new Employee(4l, "Brian", LocalDate.of(2018, Month.APRIL, 22)));
        employees.add(new Employee(3l, "David", LocalDate.of(2018, Month.APRIL, 25)));
        employees.add(new Employee(5l, "Charles", LocalDate.of(2018, Month.APRIL, 23)));
        employees.add(new Employee(2l, "Edwin", LocalDate.of(2018, Month.APRIL, 24)));
               
        employees.sort(new NameSorter());
        System.out.println(employees);
    }
}

Program output.

[
Employee [id=1, name=Alex, dob=2018-04-21], 
Employee [id=4, name=Brian, dob=2018-04-22], 
Employee [id=3, name=David, dob=2018-04-25], 
Employee [id=5, name=Charles, dob=2018-04-23], 
Employee [id=2, name=Edwin, dob=2018-04-24]]

Now let’s use the comparator classes to sort a list of age.

import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList;

public class ArrayListExample 
{
    public static void main(String[] args) throws CloneNotSupportedException 
    {
        ArrayList<Employee> employees = new ArrayList<>();
        
        employees.add(new Employee(1l, "Alex", LocalDate.of(2018, Month.APRIL, 21)));
        employees.add(new Employee(4l, "Brian", LocalDate.of(2018, Month.APRIL, 22)));
        employees.add(new Employee(3l, "David", LocalDate.of(2018, Month.APRIL, 25)));
        employees.add(new Employee(5l, "Charles", LocalDate.of(2018, Month.APRIL, 23)));
        employees.add(new Employee(2l, "Edwin", LocalDate.of(2018, Month.APRIL, 24)));
               
        employees.sort(new AgeSorter());
        System.out.println(employees);
    }
}

Program output.

[
Employee [id=1, name=Alex, dob=2018-04-21], 
Employee [id=4, name=Brian, dob=2018-04-22], 
Employee [id=5, name=Charles, dob=2018-04-23], 
Employee [id=2, name=Edwin, dob=2018-04-24], 
Employee [id=3, name=David, dob=2018-04-25]]

That’s all for the ArrayList sort() method in Java.

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs
Comparator Java Docs

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Jagga

    May 11, 2020

    o2.getName().compareToIgnoreCase(o1.getName()) if o2.getName() is null, it will throw NPE.

    • Lokesh Gupta

      May 12, 2020

      Plz add an NPE check.

  2. pango

    April 24, 2020

    return o1.getName().compareToIgnoreCase(o1.getName())

    I think you have to change in :

    return o1.getName().compareToIgnoreCase(o2.getName())

    • Lokesh Gupta

      April 27, 2020

      Thanks for reporting this typo. Much appreciated !!

  3. Manu

    January 28, 2020

    Hi Lokesh,

    In which class this sort() method present?

Comments are closed on this article!

Search Tutorials

ArrayList Methods

  • ArrayList – Introduction
  • ArrayList – add()
  • ArrayList – addAll()
  • ArrayList – clear()
  • ArrayList – clone()
  • ArrayList – contains()
  • ArrayList – ensureCapacity()
  • ArrayList – forEach()
  • ArrayList – get()
  • Arraylist – indexOf()
  • Arraylist – lastIndexOf()
  • ArrayList – listIterator()
  • ArrayList – remove()
  • ArrayList – removeAll()
  • ArrayList – removeIf()
  • ArrayList – retainAll()
  • ArrayList – sort()
  • ArrayList – spliterator()
  • ArrayList – subList()
  • ArrayList – toArray()

ArrayList Examples

  • ArrayList – Initialize arraylist
  • ArrayList – Iteration
  • ArrayList – Add/replace element
  • ArrayList – Add multiple elements
  • ArrayList – Check empty list
  • ArrayList – Remove element
  • ArrayList – Replace element
  • ArrayList – Empty arraylist
  • ArrayList – Synchronized arraylist
  • ArrayList – Compare two lists
  • ArrayList – Remove duplicates
  • ArrayList – Merge two lists
  • ArrayList – Serialization
  • ArrayList – Swap two elements
  • Convert ArrayList to Array
  • Convert Array to ArrayList
  • Convert HashSet to ArrayList
  • Convert LinkedList to ArrayList
  • Convert Vector to ArrayList
  • ArrayList vs LinkedList
  • ArrayList vs Vector

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces