Explain List Sorting in Java with example

List Sorting in Java

List Sorting in Java – sorting a list can be done in several ways, with the Collections.sort() method and using Java Streams being two of the most common approaches. Here’s a detailed explanation of both methods with examples.

Using Collections.sort()

The Collections.sort() method is a static method that sorts the specified list into ascending order, according to the natural ordering of its elements or by a Comparator provided.

Example of List Sorting in Java

Suppose we have a list of integers and we want to sort it in ascending order:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortExample {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(5);
        numbers.add(2);
        numbers.add(9);
        numbers.add(1);
        numbers.add(3);
        
        System.out.println("Before sorting: " + numbers);
        
        Collections.sort(numbers);
        
        System.out.println("After sorting: " + numbers);
    }
}

Output

Before sorting: [5, 2, 9, 1, 3]
After sorting: [1, 2, 3, 5, 9]

For custom objects, we can provide a Comparator:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

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 SortExample {
    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 25));
        people.add(new Person("Charlie", 35));
        
        System.out.println("Before sorting: " + people);
        
        Collections.sort(people, new Comparator<Person>() {
            @Override
            public int compare(Person p1, Person p2) {
                return Integer.compare(p1.age, p2.age);
            }
        });
        
        System.out.println("After sorting: " + people);
    }
}

Output

Before sorting: [Alice (30), Bob (25), Charlie (35)]
After sorting: [Bob (25), Alice (30), Charlie (35)]

Using Java Streams

Java 8 introduced the Streams API, which can be used to sort lists in a more declarative way.

Example

Using a list of integers:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StreamSortExample {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(5);
        numbers.add(2);
        numbers.add(9);
        numbers.add(1);
        numbers.add(3);
        
        System.out.println("Before sorting: " + numbers);
        
        List<Integer> sortedNumbers = numbers.stream()
                                             .sorted()
                                             .collect(Collectors.toList());
        
        System.out.println("After sorting: " + sortedNumbers);
    }
}

Output

Before sorting: [5, 2, 9, 1, 3]
After sorting: [1, 2, 3, 5, 9]

For custom objects:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

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 StreamSortExample {
    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 25));
        people.add(new Person("Charlie", 35));
        
        System.out.println("Before sorting: " + people);
        
        List<Person> sortedPeople = people.stream()
                                          .sorted((p1, p2) -> Integer.compare(p1.age, p2.age))
                                          .collect(Collectors.toList());
        
        System.out.println("After sorting: " + sortedPeople);
    }
}

Output

Before sorting: [Alice (30), Bob (25), Charlie (35)]
After sorting: [Bob (25), Alice (30), Charlie (35)]

Conclusion

Both Collections.sort() and Streams API provide efficient ways to sort lists in Java. Collections.sort() is more traditional and straightforward for simple cases, while Streams provide more flexibility and a modern, functional approach to sorting, especially useful for complex sorting criteria and operations on streams of data.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *