Java List Sorting in Java
List Sorting in Java
In Java, you can sort a List (such as ArrayList, LinkedList, etc.) using the Collections.sort() method or by using List.sort() (introduced in Java 8) in combination with a Comparator or Comparable.
There are two common approaches to sorting:
Sorting using Comparable (natural ordering).
Sorting using Comparator (custom ordering).
1. Sorting Using Comparable Interface
The Comparable interface defines a natural ordering for objects of a class. Classes that implement Comparable can be sorted using the Collections.sort() method or the List.sort() method without the need for a custom comparator.
Example: Sorting a List of String (which already implements Comparable):
import java.util.*;public class ComparableSortingExample { public static void main(String[] args) { List<String> fruits = new ArrayList<>(); fruits.add("Banana"); fruits.add("Apple"); fruits.add("Cherry"); fruits.add("Mango"); // Sorting using Comparable (natural order for Strings) Collections.sort(fruits); // Print sorted list System.out.println("Sorted List: " + fruits); }}Output:
Sorted List: [Apple, Banana, Cherry, Mango]In the above example, the String class implements Comparable, so we can directly use Collections.sort() to sort the list in alphabetical order.
2. Sorting Using Comparator Interface
If you want to define a custom sorting order, you can use the Comparator interface. This allows you to define the sorting logic by providing a custom comparator.
Example: Sorting a List of Person objects based on custom criteria (e.g., by age):
import java.util.*;class Person { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return name + " (" + age + ")"; }}public class ComparatorSortingExample { public static void main(String[] args) { List<Person> people = new ArrayList<>(); people.add(new Person("Alice", 25)); people.add(new Person("Bob", 30)); people.add(new Person("Charlie", 20)); people.add(new Person("Dave", 35)); // Sorting by age using a custom Comparator Collections.sort(people, new Comparator<Person>() { @Override public int compare(Person p1, Person p2) { return Integer.compare(p1.age, p2.age); // Sorting by age } }); // Print sorted list System.out.println("Sorted by age: " + people); }}Output:
Sorted by age: [Charlie (20), Alice (25), Bob (30), Dave (35)]Using Lambda Expression for Sorting
Since Java 8, you can use lambda expressions to simplify the code for comparators.
// Sorting by age using a lambda expressionCollections.sort(people, (p1, p2) -> Integer.compare(p1.age, p2.age));This does the same as the previous example but with a more concise syntax.
3. Sorting in Reverse Order
If you want to sort the list in reverse order, you can use Collections.reverseOrder() with a Comparator.
Example: Sorting a List of Integers in Reverse Order:
import java.util.*;public class ReverseOrderSortingExample { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(); numbers.add(5); numbers.add(2); numbers.add(8); numbers.add(1); // Sorting in reverse order Collections.sort(numbers, Collections.reverseOrder()); // Print sorted list System.out.println("Sorted in reverse order: " + numbers); }}Output:
Sorted in reverse order: [8, 5, 2, 1]4. Sorting Using List.sort() Method (Java 8+)
From Java 8 onwards, the List interface also has a sort() method that can be used to sort the list. It takes a Comparator as an argument.
Example: Sorting a List of Strings in Reverse Alphabetical Order:
import java.util.*;public class ListSortExample { public static void main(String[] args) { List<String> fruits = new ArrayList<>(); fruits.add("Banana"); fruits.add("Apple"); fruits.add("Cherry"); fruits.add("Mango"); // Sorting in reverse order using List.sort() and Comparator fruits.sort(Comparator.reverseOrder()); // Print sorted list System.out.println("Sorted List in reverse order: " + fruits); }}Output:
Sorted List in reverse order: [Mango, Cherry, Banana, Apple]5. Sorting by Multiple Criteria
You can also sort by multiple criteria by chaining comparators using thenComparing().
Example: Sorting by Age and Name:
import java.util.*;class Person { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return name + " (" + age + ")"; }}public class MultiCriteriaSortingExample { public static void main(String[] args) { List<Person> people = new ArrayList<>(); people.add(new Person("Alice", 25)); people.add(new Person("Bob", 30)); people.add(new Person("Charlie", 20)); people.add(new Person("Alice", 30)); // Sorting by age, and if ages are equal, by name people.sort(Comparator.comparingInt(Person::getAge) .thenComparing(Person::getName)); // Print sorted list System.out.println("Sorted by age and name: " + people); }}Output:
Sorted by age and name: [Charlie (20), Alice (25), Alice (30), Bob (30)]6. Sorting a List Using Java 8 Stream API
The Stream API also provides a convenient way to sort a list using sorted().
Example: Sorting a List Using Stream:
import java.util.*;import java.util.stream.*;public class StreamSortingExample { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(5, 2, 8, 1); // Sorting using Stream List<Integer> sortedNumbers = numbers.stream() .sorted() .collect(Collectors.toList()); // Print sorted list System.out.println("Sorted List: " + sortedNumbers); }}Output:
Sorted List: [1, 2, 5, 8]Conclusion
Sorting lists in Java is simple and flexible with the various sorting methods provided by the Collections class and List.sort(). You can sort based on natural ordering (using Comparable), custom sorting logic (using Comparator), or even perform more complex sorting with multiple criteria. Additionally, the Java 8 Stream API provides a more functional approach to sorting collections.
Let me know if you need further clarification or examples! ?