Skip to content

WebDevHubs

  • Home
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • Java
  • Selenium
  • PHP
  • Python
  • Programs
  • Toggle search form

Java ArrayList sort() Method

Posted on July 24, 2025July 24, 2025 By Admin No Comments on Java ArrayList sort() Method

The sort() method in Java’s ArrayList class is a highly practical feature for ordering elements in a list based on natural order or custom rules. Introduced in Java 8, this method leverages functional programming by accepting a comparator, making sorting operations on dynamic lists much simpler, more flexible, and more expressive.

What Is the sort() Method in ArrayList?

  • The sort() method sorts the elements of the ArrayList in place, modifying the original list.
  • It accepts a Comparator as an argument, defining the order for sorting.
  • If null is passed as the comparator, the list is sorted in natural order (i.e., ascending for numbers, alphabetically for strings).

Syntax

public void sort(Comparator<? super E> c)

Where:

  • c is a comparator (can be a lambda, method reference, or null for natural order).
  • E is the type of the elements in the list.

Parameters

ParameterDescription
cComparator for custom sorting; null to sort by natural order of element type.

Return Value

  • void – This method does not return a value. The list is sorted in place.

Exceptions

  • ClassCastException: Thrown if the list elements are not mutually comparable.
  • UnsupportedOperationException: Thrown if the list cannot be modified (rare; e.g., immutable lists).
  • IllegalArgumentException: If the comparator is inconsistent with equals.

How Does sort() Work Internally?

  • The sort() method uses a modified merge sort (stable, adaptive, iterative).
  • Either the provided comparator or the elements’ natural ordering (via compareTo()) is used for comparison.
  • The method is efficient and stable for lists of any size.

Examples of the sort() Method

1. Sort Strings in Alphabetical Order

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> cities = new ArrayList<>();
        cities.add("Delhi");
        cities.add("Mumbai");
        cities.add("Chennai");

        cities.sort(null); // Sorts alphabetically

        System.out.println(cities); // Output: [Chennai, Delhi, Mumbai]
    }
}

2. Sort Integers in Ascending and Descending Order

import java.util.ArrayList;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(10); numbers.add(2); numbers.add(35);

        // Sort ascending (natural order)
        numbers.sort(null);
        System.out.println(numbers); // Output: [2, 10, 35]

        // Sort descending using Comparator
        numbers.sort(Comparator.reverseOrder());
        System.out.println(numbers); // Output: [35, 10, 2]
    }
}

3. Sort Custom Objects Using Comparator

import java.util.ArrayList;
import java.util.Comparator;

class Student {
    String name;
    int age;
    Student(String name, int age) { this.name = name; this.age = age; }
    public String toString() { return name + " (" + age + ")"; }
}

public class Demo {
    public static void main(String[] args) {
        ArrayList<Student> students = new ArrayList<>();
        students.add(new Student("Alex", 23));
        students.add(new Student("Brian", 20));

        // Sort by age (ascending)
        students.sort(Comparator.comparingInt(s -> s.age));
        System.out.println(students); // Output: [Brian (20), Alex (23)]
    }
}

4. Sort Strings by Length Using Lambda

import java.util.ArrayList;

public class Example {
    public static void main(String[] args) {
        ArrayList<String> animals = new ArrayList<>();
        animals.add("Elephant");
        animals.add("Dog");
        animals.add("Cat");

        // Sort by string length (ascending)
        animals.sort((a, b) -> Integer.compare(a.length(), b.length()));
        System.out.println(animals); // Output: [Dog, Cat, Elephant]
    }
}

Important Notes

  • In-place sorting: The original list is reordered; sorting does not create a new list.
  • Null values: If present, sort() may throw NullPointerException.
  • Natural order: Use null as the comparator to sort with the natural order of the list’s elements.
  • Custom rules: You can use lambdas or method references to provide complex sorting logic.
  • Stability: Sorting is stable—equal elements retain their original position.

Summary

AspectDetails
Method PurposeSorts elements in an ArrayList in place
Syntaxlist.sort(Comparator<? super E> c)
ParametersComparator for custom order (or null for natural)
Return ValueNone (void)
ExceptionsClassCastException, NullPointerException, UnsupportedOperationException
Typical Use CasesAlphabetical sorting, numeric sorting, custom order

Typical Use Cases

  • Sorting data for display (e.g., names, numbers, custom objects).
  • Batch processing where results need to be in order for further tasks.
  • Data normalization and presentation, such as reports, charts, or UIs.
  • Custom ranking (leaderboards, top-N lists, etc.).
Java Tags:Java-ArrayList, Java-ArrayList-Method, Java-Collections

Post navigation

Previous Post: Java ArrayList size() Method
Next Post: Java ArrayList spliterator() Method

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Java ArrayList
  • Java ArrayList Methods
  • Java ArrayList add() Method
  • Java ArrayList addAll() Method
  • Java ArrayList clear() Method
  • Java ArrayList clone() Method
  • Java ArrayList contains() Method
  • Java ArrayList ensureCapacity() Method
  • Java ArrayList forEach() Method
  • Java ArrayList get() Method
  • Java ArrayList indexOf() Method
  • Java ArrayList isEmpty() Method
  • Java ArrayList iterator() Method
  • Java ArrayList lastIndexOf() Method
  • Java ArrayList listIterator() Method
  • Java ArrayList remove() Method
  • Java ArrayList removeAll() Method
  • Java ArrayList removeIf() Method
  • Java ArrayList replaceAll() Method
  • Java ArrayList retainAll() Method
  • Java ArrayList set() Method
  • Java ArrayList size() Method
  • Java ArrayList sort() Method
  • Java ArrayList spliterator() Method
  • Java ArrayList subList() Method
  • Java ArrayList toArray() Method
  • Java ArrayList trimToSize() Method

Recent Posts

  • Java ArrayList trimToSize() Method
  • Java ArrayList toArray() Method
  • Java ArrayList subList() Method
  • Java ArrayList spliterator() Method
  • Java ArrayList sort() Method

Recent Comments

No comments to show.

Important Pages

  • About Us
  • Contact Us
  • Terms of Use
  • Privacy Policy

Web Development

  • HTML
  • CSS
  • JavaScript
  • PHP

Programming Languages

  • Java
  • Python
  • PHP
  • Programs

Others

  • Selenium
  • Lodash
  • Java ArrayList
  • JavaScript Array Methods

Copyright © 2025 WebDevHubs.

Powered by PressBook Green WordPress theme