Java – How to sort LinkedList using Collections.sort() method

In this article, we will discuss how to sort LinkedList elements in ascending & descending order using Collections.sort() method

1. Collections.sort() method

  • Sorts the specified list into ascending order, according to the natural ordering of its elements
  • All elements in the list must implement the Comparable interface
  • Furthermore, all elements in the list must be mutually comparable
  • That is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list
  • This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort
  • String and wrapper classes implements comparable interface, so when we store elements of String type then we can use Collections’ sort() method to sort elements in ascending order of alphabets
  • Note: there shouldn’t be any NULL objects, otherwise NullPointerException will be thrown
  • Method signature :- public static <T extends Comparable<? super T>> void sort(List<T> list)

1.1 Sorting LinkedList of Integer numbers

  • A LinkedList contains integer numbers in insertion-order
  • We are sorting these integer numbers in natural order (or ascending order) using Collections.sort() method

SortLinkedListOfIntegerUsingCollectionsSortMethod.java

package net.bench.resources.sort.linkedlist.java;

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

public class SortLinkedListOfIntegerUsingCollectionsSortMethod {

	public static void main(String[] args) {

		// 1. create LinkedList
		List<Integer> numbers = new LinkedList<>();


		// 1.2 add integer numbers to LL
		numbers.add(87);
		numbers.add(18);
		numbers.add(98);
		numbers.add(64);
		numbers.add(25);
		numbers.add(77);
		numbers.add(54);


		// 1.3 original LinkedList in insertion order
		System.out.println("1. Original LinkedList<Integer> "
				+ "as per insertion-order :- \n");


		// 1.4 Iterating using enhanced for-loop
		for(int num : numbers){
			System.out.println(num);
		}


		// 2. Collections.sort() - natural order
		Collections.sort(numbers);


		// 2.1 print to console
		System.out.println("\n2. Natural order of "
				+ "LinkedList<Integer> :- \n");


		// 2.2 Iterating using enhanced for-loop
		for(int num : numbers){
			System.out.println(num);
		}


		// 3. Collections.sort() - reverse order
		Collections.sort(numbers, Comparator.reverseOrder());


		// 3.1 print to console
		System.out.println("\n3. Reverse order of "
				+ "LinkedList<Integer> :- \n");


		// 3.2 Iterating using enhanced for-loop
		for(int num : numbers){
			System.out.println(num);
		}
	}
}

Output:

1. Original LinkedList<Integer> as per insertion-order :- 

87
18
98
64
25
77
54

2. Natural order of LinkedList<Integer> :- 

18
25
54
64
77
87
98

3. Reverse order of LinkedList<Integer> :- 

98
87
77
64
54
25
18

1.2 Sorting LinkedList of String elements

  • A LinkedList contains String elements in insertion-order
  • We are sorting these String elements in alphabetical order using Collections.sort() method

SortLinkedListOfStringUsingCollectionsSortMethod.java

package net.bench.resources.sort.linkedlist.java;

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

public class SortLinkedListOfStringUsingCollectionsSortMethod {

	public static void main(String[] args) {

		// 1. create LinkedList
		List<String> names = new LinkedList<>();


		// 1.1 add names to LL
		names.add("Karthik");
		names.add("Nagarjuna");
		names.add("Ramki");
		names.add("Surya");
		names.add("Ajith");
		names.add("Prasanna");


		// 1.2 original LinkedList as per insertion order
		System.out.println("1. Original LinkedList<String> "
				+ "as per insertion-order :- \n");


		// 1.3 Iterating using enhanced for-loop
		for(String str : names){
			System.out.println(str);
		}


		// 2. Collections.sort() - alphabetical order
		Collections.sort(names);


		// 2.1 print to console
		System.out.println("\n2. Alphabetically sorted-order "
				+ "of LinkedList<String> :- \n");


		// 2.2 Iterating using enhanced for-loop
		for(String str : names){
			System.out.println(str);
		}


		// 3. Collections.sort() - reverse alphabetical order
		Collections.sort(names, new Comparator<String>() {

			@Override
			public int compare(String str1, String str2) {
				return str2.compareTo(str1);
			}
		});


		// 3.1 print to console
		System.out.println("\n3. Reverse alphabetically sorted-order "
				+ "of LinkedList<String> :- \n");


		// 3.2 Iterating using enhanced for-loop
		for(String str : names){
			System.out.println(str);
		}
	}
}

Output:

1. Original LinkedList<String> as per insertion-order :- 

Karthik
Nagarjuna
Ramki
Surya
Ajith
Prasanna

2. Alphabetically sorted-order of LinkedList<String> :- 

Ajith
Karthik
Nagarjuna
Prasanna
Ramki
Surya

3. Reverse alphabetically sorted-order of LinkedList<String> :- 

Surya
Ramki
Prasanna
Nagarjuna
Karthik
Ajith

2. Comparable interface & Collections.sort() method

  • Compares this object with the specified object for order
  • Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object
  • Method signature :- int compareTo(T object)

2.1 Sorting LinkedList of Student objects

  • A LinkedList contains Student objects with attributes such as Id, name and their age in insertion-order
  • We are sorting these Student objects in natural order according to their age using Collections.sort() method

Student.java

package net.bench.resources.sort.linkedlist.java;

public class Student implements Comparable<Student>  {

	// member variables
	private int id;
	private String name;
	private int age;

	// 3-arg parameterized constructor

	// getters & setters

	// toString()


	// compareTo()
	@Override
	public int compareTo(Student s) {
		return Integer.compare(this.age, s.getAge());
	}
}

SortLinkedListOfIntegerUsingStream.java

package net.bench.resources.sort.linkedlist.java;

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

public class SortLinkedListOfStudentsUsingCollectionsSortMethod {

	public static void main(String[] args) {

		// 1. create LinkedList
		List<Student> students = new LinkedList<>();


		// 1.1 add Students to LL
		students.add(new Student(2063, "Pravin", 35));
		students.add(new Student(2097, "Shweta", 32));
		students.add(new Student(2019, "Sachin", 28));
		students.add(new Student(2023, "Kalpana", 27));
		students.add(new Student(2045, "Rajdeepan", 31));
		students.add(new Student(2073, "Sneha", 24));


		// 1.2 original LinkedList in insertion order
		System.out.println("1. Original LinkedList "
				+ "as per insertion-order :- \n");


		// 1.3 Iterating using enhanced for-loop
		for(Student student : students){
			System.out.println(student);
		}


		// 2. Collections.sort() - increasing-order of Age
		Collections.sort(students);


		// 2.1 print to console
		System.out.println("\n2. Sorted Student LinkedList -"
				+ " according to Age :- \n");


		// 2.2 Iterating using enhanced for-loop
		for(Student student : students){
			System.out.println(student);
		}


		// 3. Collections.sort() - decreasing-order of Age
		Collections.sort(students, new Comparator<Student>() {

			@Override
			public int compare(Student stud1, Student stud2) {
				return stud2.getAge() - stud1.getAge();
			}
		});


		// 3.1 print to console
		System.out.println("\n3. Reverse sorted Student LinkedList -"
				+ " according to Age :- \n");


		// 3.2 Iterating using enhanced for-loop
		for(Student student : students){
			System.out.println(student);
		}
	}
}

Output:

1. Original LinkedList as per insertion-order :- 

Student [id=2063, name=Pravin, age=35]
Student [id=2097, name=Shweta, age=32]
Student [id=2019, name=Sachin, age=28]
Student [id=2023, name=Kalpana, age=27]
Student [id=2045, name=Rajdeepan, age=31]
Student [id=2073, name=Sneha, age=24]

2. Sorted Student LinkedList - according to Age :- 

Student [id=2073, name=Sneha, age=24]
Student [id=2023, name=Kalpana, age=27]
Student [id=2019, name=Sachin, age=28]
Student [id=2045, name=Rajdeepan, age=31]
Student [id=2097, name=Shweta, age=32]
Student [id=2063, name=Pravin, age=35]

3. Reverse sorted Student LinkedList - according to Age :- 

Student [id=2063, name=Pravin, age=35]
Student [id=2097, name=Shweta, age=32]
Student [id=2045, name=Rajdeepan, age=31]
Student [id=2019, name=Sachin, age=28]
Student [id=2023, name=Kalpana, age=27]
Student [id=2073, name=Sneha, age=24]

3. Comparator interface & Collections.sort() method

  • Compares its two arguments for order
  • Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second argument
  • Method signature :- int compare(T object1, T object2)

3.1 Sorting LinkedList of Student objects

  • A LinkedList contains Student objects with attributes such as Id, name and their age in insertion-order
  • We are sorting these Student objects in natural order according to their name using Collections.sort() method

Student.java

package net.bench.resources.sort.linkedlist.java;

public class Student {

	// member variables
	private int id;
	private String name;
	private int age;

	// 3-arg parameterized constructor

	// getters & setters

	// toString()
}

StudentComparator.java

package net.bench.resources.sort.linkedlist.java;

import java.util.Comparator;

public class StudentComparator implements Comparator<Student> {

	// name comparison in alphabetical order
	@Override
	public int compare(Student student1, Student student2) {
		return student1.getName().compareTo(student2.getName());
	}
}

SortLinkedListOfStudentsUsingComparator.java

package net.bench.resources.sort.linkedlist.java;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class SortLinkedListOfStudentsUsingComparator {

	public static void main(String[] args) {

		// 1. create LinkedList
		List<Student> students = new LinkedList<>();


		// 1.1 add Students to LL
		students.add(new Student(2063, "Pravin", 35));
		students.add(new Student(2097, "Abhijeet", 32));
		students.add(new Student(2019, "Sachin", 28));
		students.add(new Student(2023, "Kalpana", 27));
		students.add(new Student(2045, "Rajdeepan", 31));
		students.add(new Student(2073, "Nikita", 24));


		// 1.2 original LinkedList in insertion order
		System.out.println("1. Original LinkedList "
				+ "as per insertion-order :- \n");


		// 1.3 Iterating using enhanced for-loop
		for(Student student : students){
			System.out.println(student);
		}


		// 2. Collections.sort() - alphabetical order of Name
		Collections.sort(students, new StudentComparator());


		// 2.1 print to console
		System.out.println("\n2. Sorted Student LinkedList -"
				+ " according to Name :- \n");


		// 2.2 Iterating using enhanced for-loop
		for(Student student : students){
			System.out.println(student);
		}


		// 3. Collections.sort() - reverse alphabetical order of Name
		Collections.sort(students, (new StudentComparator()).reversed());


		// 3.1 print to console
		System.out.println("\n3. Reverse sorted Student LinkedList -"
				+ " according to Name :- \n");


		// 3.2 Iterating using enhanced for-loop
		for(Student student : students){
			System.out.println(student);
		}
	}
}

Output:

1. Original LinkedList as per insertion-order :- 

Student [id=2063, name=Pravin, age=35]
Student [id=2097, name=Abhijeet, age=32]
Student [id=2019, name=Sachin, age=28]
Student [id=2023, name=Kalpana, age=27]
Student [id=2045, name=Rajdeepan, age=31]
Student [id=2073, name=Nikita, age=24]

2. Sorted Student LinkedList - according to Name :- 

Student [id=2097, name=Abhijeet, age=32]
Student [id=2023, name=Kalpana, age=27]
Student [id=2073, name=Nikita, age=24]
Student [id=2063, name=Pravin, age=35]
Student [id=2045, name=Rajdeepan, age=31]
Student [id=2019, name=Sachin, age=28]

3. Reverse sorted Student LinkedList - according to Name :- 

Student [id=2019, name=Sachin, age=28]
Student [id=2045, name=Rajdeepan, age=31]
Student [id=2063, name=Pravin, age=35]
Student [id=2073, name=Nikita, age=24]
Student [id=2023, name=Kalpana, age=27]
Student [id=2097, name=Abhijeet, age=32]

References:

Happy Coding !!
Happy Learning !!

Java – How to sort TreeSet in descending order using Comparator
Java - How to remove elements from LinkedList