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());