Explain Codes LogoExplain Codes Logo

How to sort a List/ArrayList?

java
comparators
lambda
collections
Nikita BarsukovbyNikita BarsukovΒ·Oct 22, 2024
⚑TLDR

To arrange your troops (elements of List) in Java, instantly resort to Collections.sort(list). For ascending reconnaissance, use this; else for custom war strategy include a Comparator: Collections.sort(list, Comparator.reverseOrder()). Java 8 gives us Gandalf's staff (list.sort(Comparator.naturalOrder()) for ascending, or list.sort(Comparator.reverseOrder()) for descending order.

List<String> fruits = Arrays.asList("Apple", "Orange", "Banana"); // Sort alphabetically Collections.sort(fruits); // Apple always comes first // Or using Java 8+ for reverse order fruits.sort(Comparator.reverseOrder()); // Trivia: "Orange" is now in the first place 🍊

For classic sorting, blindly go for Collections.sort(), but for readability and flexible codes, List.sort() with Java 8+ brings the magic.

Ease your troubles with Comparators

With Comparators, define your sorting logic to ease your troubles. These can either be traditional anonymous classes or extremely simple lambda expressions:

// Sorting with a custom Comparator for reverse order Collections.sort(fruits, (a, b) -> b.compareTo(a)); // It's time for bananas 🍌 to get highlighted // You can fluently use method references and reversed() for descending order with custom types List<CustomObject> objects = //... Collections.sort(objects, Comparator.comparing(CustomObject::getField).reversed()); // You see the magic, right?

For Java 8 stream fans, the sorted() function makes sorting relaxing and effortless:

List<Double> doubles = Arrays.asList(3.14, 1.68, 2.19); // Sort doubles in reverse order List<Double> sortedDoubles = doubles.stream() .sorted(Comparator.reverseOrder()) .collect(Collectors.toList());

Match up with the perfect Comparator

Java confers the ability of using ternary operator shorthands along with type inference, helping you write custom comparators to run for the specific landmark:

// Ternary shorthand in a custom Comparator Collections.sort(numbers, (a, b) -> (a < b) ? 1 : ((a.equals(b)) ? 0 : -1));

Lambdas and method references: Ease your burden

With lambda expressions and method references, retain your code's brevity and readability, especially while implementing single-method interfaces like Comparator:

// Lambda and method reference for comparing complex objects Collections.sort(people, Comparator.comparing(Person::getLastName).thenComparing(Person::getFirstName));

Advanced Collections Sorting

Apply the Collections library to meet your complex sorting demands:

Sorting in descending order

For descending view of your list, sort it first and then reverse. The magic:

Collections.sort(fruits); // Natural (ascending) order Collections.reverse(fruits); // Voila! It's in descending order now

The power of Stream API

Incredibly powerful sorting methods await with the Stream API. In-line custom sorting is also possible with Comparator.comparing().reversed():

List<CustomObject> complexList = //... List<CustomObject> sortedComplexList = complexList.stream() .sorted(Comparator.comparing(CustomObject::getField).reversed()) .collect(Collectors.toList());

Non-destructive sorting is what Streams offer, so no worries about altering your original list.