Programming
Java
ArrayList
Data Structures
Sorting Algorithms

How to sort a List/ArrayList?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Sorting a List or ArrayList is a common operation in software development, allowing data to be organized in a specific order. In programming languages like Java, a List is an ordered collection (also known as a sequence). The List interface provides a way to store the ordered collection. An ArrayList is a resizable-array implementation of the List interface. Below, we explore different methods and techniques for sorting these collections, particularly focusing on Java.

Sorting using Collections.sort()

In Java, the Collections.sort() method is one of the most common ways to sort an ArrayList. This method sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. The elements' natural ordering must be consistent with equals if it is to correctly sort a list.

Example:

java
1import java.util.*;
2
3public class Main {
4    public static void main(String[] args) {
5        List<String> fruits = new ArrayList<>();
6        fruits.add("Orange");
7        fruits.add("Apple");
8        fruits.add("Banana");
9        
10        Collections.sort(fruits);
11        
12        System.out.println("Sorted List: " + fruits);
13    }
14}

In the example, fruits is an ArrayList that gets sorted alphabetically.

Sorting with a Custom Comparator

You may want to sort objects in a way that does not follow their natural order. For this, Java offers the Comparator interface, which you can pass as the second argument to the Collections.sort() method.

Example:

java
1import java.util.*;
2
3public class Main {
4    public static void main(String[] args) {
5        List<Employee> employees = new ArrayList<>();
6        employees.add(new Employee(1, "John"));
7        employees.add(new Employee(2, "Ana"));
8        employees.add(new Employee(3, "Carlos"));
9
10        Collections.sort(employees, new Comparator<Employee>() {
11            public int compare(Employee e1, Employee e2) {
12                return e1.getName().compareTo(e2.getName());
13            }
14        });
15
16        for (Employee emp : employees) {
17            System.out.println(emp.getName());
18        }
19    }
20}
21
22class Employee {
23    private int id;
24    private String name;
25    
26    public Employee(int id, String name) {
27        this.id = id;
28        this.name = name;
29    }
30    
31    public String getName() {
32        return name;
33    }
34}

In this example, employees are sorted by their name using a custom Comparator.

Using Java 8 Stream API

Java 8 introduced the Stream API, which provides a more declarative approach to handling collections, including sorting.

Example:

java
1import java.util.*;
2import java.util.stream.Collectors;
3
4public class Main {
5    public static void main(String[] args) {
6        List<String> fruits = Arrays.asList("Orange", "Apple", "Banana");
7
8        List<String> sortedFruits = fruits.stream()
9            .sorted()
10            .collect(Collectors.toList());
11        
12        System.out.println("Sorted List: " + sortedFruits);
13    }
14}

Here, sorted() sorts the elements according to their natural order and the result is collected back into a list.

Summary Table

MethodDescriptionSuitable for
Collections.sort()Sorts based on natural ordering or using a custom comparator.Simple types and when custom comparator is needed.
Java 8 Stream API sorted()Provides a declarative way to sort collections using stream operations.Modern Java environments, when working with streams.

Additional Techniques and Considerations

  • Stability: When sorting with custom comparators, consider whether the sort needs to be stable (order of equal elements is preserved). Java's sort is stable by nature.
  • Performance: Always consider the performance implications of sorting, especially with large lists. The sort operation usually has a time complexity of O(nlog⁡n)O(n \log n).
  • Null Elements: If the list contains null values, ensure that the comparator can handle nulls, or use methods like Comparator.nullsFirst() or Comparator.nullsLast().

By understanding these different methods and considerations, you can use Java's powerful capabilities to sort lists and ArrayLists effectively and efficiently.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms