What is a List Sorting in Java?

What is List Sorting?

Sorting a list means arranging its elements in a particular order, usually ascending (small to large) or descending (large to small).

Sorting makes your data easier to read, search, and analyze, especially when dealing with large collections like names, numbers, or objects.

Java provides built-in tools to make sorting very easy and fast. Such as:

  • Collections.sort()
  • Comparator

Why Sort a List in Java?

Sorting a list can be crucial for a variety of reasons:

  • Organizing Data: For example, if you have a list of student names or employee IDs, sorting them alphabetically or numerically helps you read, locate, and manage entries quickly.
  • Efficient Searching: Sorting improves search performance, especially when dealing with large datasets.
  • Data Analysis: Sorting is also very useful in data analysis, where you may need to find patterns such as the top performer, the lowest marks, or the best-selling product.
  • User-Friendly Presentation: These types of applications and websites, which show data in a sorted manner, improve user experience.

Java List Sorting Methods

Java provides multiple ways to sort a List:

  1. Natural Sorting using Collections.sort()
  2. Custom Sorting using Comparator
  3. Sorting with Java 8 Streams

Let’s explore each method with simple examples

1. Sorting using Collections.sort() (Natural Sorting)

This is the most basic way to sort a list. Java’s Collections.sort() method automatically arranges elements in natural order. This works only when your elements implement the Comparable interface (which most built-in types like Integer and String already do).

Example: Sorting Numbers in Ascending Order

import java.util.*;

public class NumberSortExample {
public static void main(String[] args) {
// Create a list of integers
List<Integer> marks = new ArrayList<>();
marks.add(85);
marks.add(40);
marks.add(70);
marks.add(95);

// Sort the list in ascending order
Collections.sort(marks);

// Display the sorted list
System.out.println("Sorted Marks: " + marks);
}
}

Output:

Sorted Marks: [40, 70, 85, 95]

Explanation:

  • The list of numbers is sorted in ascending order because Integer implements the Comparable interface, which defines the natural ordering.

2. Custom Sorting with Comparator

Sometimes, you want a custom rule for sorting, like sorting names by length, sorting objects by price, or sorting in reverse order. In such cases, you can use the Comparator interface, which allows you to define your own sorting logic.

Example: Sorting a List of Strings by Length

import java.util.*;

public class WordLengthSort {
public static void main(String[] args) {
// Create a list of words
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Fig");
fruits.add("Banana");
fruits.add("Grapes");

// Sort by length of each word
Collections.sort(fruits, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return Integer.compare(a.length(), b.length());
}
});

// Display sorted list
System.out.println("Sorted by Length: " + fruits);
}
}

Output:

Sorted by Length: [Fig, Apple, Grapes, Banana]

Using Lambda Expressions for Simplicity

Java 8 made this process easier with lambda expressions. You can write the same sorting logic in a single line:

Collections.sort(fruits, (a, b) -> Integer.compare(a.length(), b.length()));

This makes the code shorter and more readable, perfect for modern Java projects.

3. Sorting using Java 8 Streams

Java 8 introduced the Stream API, which allows a more functional and clean way to sort data. The sorted() method can sort elements naturally or using a custom comparator.

Example: Sorting a List Using Streams

import java.util.*;
import java.util.stream.Collectors;

public class StreamSortExample {
public static void main(String[] args) {
// Original list of numbers
List<Integer> scores = Arrays.asList(50, 90, 30, 70, 10);

// Sort the list using streams
List<Integer> sortedScores = scores.stream()
.sorted()
.collect(Collectors.toList());

// Display the sorted list
System.out.println("Sorted Scores: " + sortedScores);
}
}

Output:

Sorted Scores: [10, 30, 50, 70, 90]
  • In this code, the stream() method converts the list into a stream, sorted() arranges the elements in ascending order, and collect(Collectors.toList()) converts it back to a normal list.

Example of Sorting in Reverse Order using Streams

You can also pass a custom Comparator to the sorted() method.

List<Integer> reverseSorted = scores.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());

System.out.println("Reverse Sorted: " + reverseSorted);

Output:

Reverse Sorted: [90, 70, 50, 30, 10]

This shows how easily you can switch between ascending and descending order using streams.

4. Sorting in Descending Order

By default, Java sorts elements in ascending order (smallest to largest). But sometimes, you may want to arrange data in descending order, for example, showing top scores, highest salaries, or latest dates first.

Example: Sorting Numbers in Descending Order

import java.util.*;

public class ReverseOrderExample {
public static void main(String[] args) {
// Create a list of numbers
List<Integer> numbers = new ArrayList<>();
numbers.add(8);
numbers.add(3);
numbers.add(10);
numbers.add(5);

// Sort numbers in descending order
Collections.sort(numbers, Collections.reverseOrder());

// Display the result
System.out.println("Numbers in Descending Order: " + numbers);
}
}

Output:

Numbers in Descending Order: [10, 8, 5, 3]

Example 2: Descending Order using Custom Comparator

If you want to define your own sorting rule, you can use a custom comparator.

import java.util.*;

public class CustomDescendingExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ankit");
names.add("Vijay");
names.add("Meera");
names.add("Bhavya");

// Sort in descending alphabetical order
Collections.sort(names, (a, b) -> b.compareTo(a));

System.out.println("Names in Descending Order: " + names);
}
}

Output:

Names in Descending Order: [Vijay, Meera, Bhavya, Ankit]
  • Here, (a, b) -> b.compareTo(a) reverses the comparison logic, so the sorting happens from Z → A instead of A → Z.

5. Sorting with Multiple Criteria

Sometimes, we want to sort students by name, but if two have the same name, then sort them by marks.

Java provides thenComparing() method to do a multi-level sorting.

Example: Sort by Name and then by Age

import java.util.*;

public class MultiLevelSortExample {
public static void main(String[] args) {
// Create a list of people
List<Person> people = new ArrayList<>();
people.add(new Person("Ravi", 24));
people.add(new Person("Anita", 28));
people.add(new Person("Ravi", 21));
people.add(new Person("Mehul", 25));

// Sort by name first, then by age
Collections.sort(people, Comparator.comparing(Person::getName)
.thenComparing(Person::getAge));

// Display the sorted list
for (Person p : people) {
System.out.println(p.getName() + " - " + p.getAge());
}
}
}

// Person class
class Person {
private String name;
private int age;

Person(String name, int age) {
this.name = name;
this.age = age;
}

public String getName() { return name; }
public int getAge() { return age; }
}

Output:

Anita - 28
Mehul - 25
Ravi - 21
Ravi - 24

Also Learn Important Topics of Java

Leave a Comment