0
0
JavaHow-ToBeginner · 3 min read

How to Sort List in Java: Simple Guide with Examples

To sort a list in Java, use Collections.sort(list) for natural order sorting or list.sort(Comparator) for custom order. Both methods modify the original list to be sorted.
📐

Syntax

There are two common ways to sort a list in Java:

  • Collections.sort(list): Sorts the list in natural order (like numbers ascending or strings alphabetically).
  • list.sort(Comparator): Sorts the list using a custom rule you provide with a Comparator.
java
import java.util.*;

// Sort list in natural order
Collections.sort(list);

// Sort list with custom comparator
list.sort(Comparator.reverseOrder());
💻

Example

This example shows how to sort a list of numbers in ascending order using Collections.sort() and in descending order using list.sort() with a comparator.

java
import java.util.*;

public class SortListExample {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(Arrays.asList(5, 3, 8, 1, 9));

        // Sort in ascending order
        Collections.sort(numbers);
        System.out.println("Ascending: " + numbers);

        // Sort in descending order
        numbers.sort(Comparator.reverseOrder());
        System.out.println("Descending: " + numbers);
    }
}
Output
Ascending: [1, 3, 5, 8, 9] Descending: [9, 8, 5, 3, 1]
⚠️

Common Pitfalls

Common mistakes when sorting lists in Java include:

  • Trying to sort a list of objects without implementing Comparable or providing a Comparator.
  • Expecting Collections.sort() or list.sort() to return a new sorted list (they sort the list in place).
  • Using Arrays.sort() on a list instead of an array.
java
import java.util.*;

public class SortPitfall {
    public static void main(String[] args) {
        List<Object> items = new ArrayList<>();
        items.add(new Object());
        items.add(new Object());

        // Wrong: This will throw ClassCastException
        // Collections.sort(items);

        // Right: Provide a Comparator or use Comparable objects
    }
}
📊

Quick Reference

Summary tips for sorting lists in Java:

  • Use Collections.sort(list) for natural order sorting.
  • Use list.sort(Comparator) for custom sorting rules.
  • Sorting modifies the original list; it does not create a new one.
  • Ensure list elements implement Comparable or provide a Comparator.

Key Takeaways

Use Collections.sort(list) to sort a list in natural order in Java.
Use list.sort(Comparator) to sort with custom rules.
Sorting changes the original list; it does not return a new list.
List elements must implement Comparable or you must provide a Comparator.
Avoid sorting lists of objects without proper comparison logic to prevent errors.