Sorting ArrayList Tutorial

Sorting is a very common operation that we need to do when we are working with collections. In this tutorial, we will discuss multiple ways to sort an ArrayList in Java.

1. Sorting using Collections.sort()

Using Collections.sort() method is the simplest way to sort a list.

import java.util.Collections;

Collections.sort(fruits);  // Ascending order
Collections.sort(fruits, Collections.reverseOrder()); // Descending order

2. Sorting using List.sort() (Java 8)

In Java 8, `List` interface introduced a default method `sort`.

fruits.sort(Comparator.naturalOrder()); // Ascending
fruits.sort(Comparator.reverseOrder()); // Descending

3. Sorting using Lambda Expressions

// Sort by length
fruits.sort((s1, s2) -> s1.length() - s2.length());

4. Sorting using Method Reference

fruits.sort(String::compareTo);

5. Sorting using Streams

List<String> sortedList = fruits.stream()
    .sorted()
    .collect(Collectors.toList());

Frequently Asked Questions

What will I learn here?

This page covers the core concepts and techniques you need to understand the topic and progress confidently to the next lesson.

How should I use this page?

Start with the overview, then follow the section links to deepen your understanding. Use the table of contents on the right to jump to specific sections.

What should I read next?

Use the navigation below to continue to the next lesson or explore related topics.