Collections.sort() in Java with Examples

The Collections.sort() method is used to sort elements in a List in Java. It provides a convenient way to sort lists either in natural order or using a custom comparator.

Collections.sort() Key Points

  1. For Lists Only: It works exclusively with List implementations, such as ArrayList or LinkedList.
  2. Natural Ordering: Uses the Comparable interface if no comparator is provided.
  3. Custom Sorting: Allows sorting based on any custom logic using a Comparator.
  4. Efficiency: Uses TimSort, which has a time complexity of O(n log⁡n).

Collections.sort() Method Signature

  1. For Natural Ordering:
    public static <T extends Comparable<? super T>> void sort(List<T> list)
  2. For Custom Ordering:
    public static <T> void sort(List<T> list, Comparator<? super T> c)

Collections.sort() method Examples in Java

1. Sorting a List of Integers in Natural Order

Demonstrates sorting a list of integers in ascending order using Collections.sort().

package com.javacodepoint.sort;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionSort1 {
	
	public static void main(String[] args) {
		List<Integer> numbers = Arrays.asList(10, 5, 8, 1, 7);

		System.out.println("Original List: " + numbers);

		// Sort the list
		Collections.sort(numbers);

		System.out.println("Sorted List: " + numbers);
	}
}

OUTPUT:

2. Sorting a List of Strings in Natural Order

Shows how to alphabetically sort a list of strings with Collections.sort().

package com.javacodepoint.sort;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionSort2 {

	public static void main(String[] args) {
		List<String> names = Arrays.asList("John", "Alice", "Bob", "Diana");

		System.out.println("Original List: " + names);

		// Sort the list
		Collections.sort(names);

		System.out.println("Sorted List: " + names);
	}
}

OUTPUT:

3. Sorting a List in Reverse Order Using a Comparator

Explains sorting a list of integers in descending order using a custom comparator with Collections.reverseOrder().

package com.javacodepoint.sort;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionSort3 {

	public static void main(String[] args) {
		List<Integer> numbers = Arrays.asList(10, 5, 8, 1, 7);

		System.out.println("Original List: " + numbers);

		// Sort the list in reverse order
		Collections.sort(numbers, Collections.reverseOrder());

		System.out.println("Sorted List (Reverse Order): " + numbers);
	}
}

OUTPUT:

4. Sorting Custom Objects Using Natural Order (Comparable)

Sorts a list of custom objects (e.g., Student) based on a natural property (e.g., age) defined in the class itself. The custom class (e.g., Student) implements the Comparable interface. The compareTo() method is overridden to define the natural order logic (e.g., comparing ages).

package com.javacodepoint.sort;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

class Student implements Comparable<Student> {
    String name;
    int age;

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

    @Override
    public int compareTo(Student other) {
        return this.age - other.age; // Sort by age
    }

    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}

public class CollectionSort4 {
	
	public static void main(String[] args) {
        List<Student> students = Arrays.asList(
            new Student("Alice", 22),
            new Student("Bob", 20),
            new Student("Charlie", 23)
        );

        System.out.println("Original List: " + students);

        // Sort the list by natural order (age)
        Collections.sort(students);

        System.out.println("Sorted List by Age: " + students);
    }
}

OUTPUT:

5. Sorting Custom Objects Using Custom Comparator

Sorts a list of custom objects (e.g., Student) based on a specific property (e.g., name, grade, or salary) that might not be the default or natural order.

Sorting Logic: The comparator is a functional interface, often implemented using a lambda expression. For example, to sort students by their name, a comparator is written as: (s1, s2) -> s1.name.compareTo(s2.name)

package com.javacodepoint.sort;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

class Student {
	String name;
	int age;

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

	@Override
	public String toString() {
		return name + " (" + age + ")";
	}
}

public class CollectionSort5 {

	public static void main(String[] args) {
		List<Student> students = Arrays.asList(new Student("Alice", 22), new Student("Bob", 20),
				new Student("Charlie", 23));

		System.out.println("Original List: " + students);

		// Sort the list by name
		Collections.sort(students, (s1, s2) -> s1.name.compareTo(s2.name));

		System.out.println("Sorted List by Name: " + students);
	}
}

OUTPUT:

Java logical programs list


Java Basic Programs

Java String Programs

Java Miscellaneous Programs

Java Programs based on the Collection Framework

Leave a Reply

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