Java 8 – How to sort LinkedList using Stream

In this article we will discuss different ways to sort LinkedList elements using Java 8

Before proceeding with this sorting examples understand below items,

1. Stream.sorted() method

  • This Stream method is an stateful intermediate operation which sorts elements present in the stream according to natural order
  • If elements present in the stream aren’t Comparable then java.lang.ClassCastException is thrown when final terminal operation is executed
  • For ordered streams, the sort is stable
  • For unordered streams, no stability guarantees are made
  • Method signature 1 :- Stream<T> sorted()
  • Method signature 2 :- Stream<T> sorted(Comparator<? super T> comparator)

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 Java 8 Stream’s sorted() method

SortLinkedListOfIntegerUsingStream.java

package net.bench.resources.sort.linkedlist;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

public class SortLinkedListOfIntegerUsingStream {

	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");
		numbers.forEach(System.out::println);


		// 2. Stream.sorted() - natural order
		List<Integer> sortedNumbers = numbers
				.stream()
				.sorted()
				.collect(Collectors.toList());


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


		// 3.  Stream.sorted() - reverse order
		List<Integer> reverseSortedNumber = numbers
				.stream()
				.sorted(Comparator.reverseOrder())
				.collect(Collectors.toList());


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

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 Java 8 Stream’s sorted() method

SortLinkedListOfStringUsingStream.java

package net.bench.resources.sort.linkedlist;

import java.util.LinkedList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SortLinkedListOfStringUsingStream {

	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 in insertion order
		System.out.println("1. Original LinkedList<String> "
				+ "as per insertion-order :- \n");
		names.forEach(System.out::println);


		// 2. sort using Stream - alphabetical order
		List<String> sortedNames = names
				.stream()
				.sorted()
				.collect(Collectors.toList());


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


		// 3. sort using Stream - reverse alphabetical order
		List<String> reverseSortedNames = names
				.stream()
				.sorted(Comparator.reverseOrder())
				.collect(Collectors.toList());


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

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

1.3 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 and their Id in descending order using Java 8 Stream’s sorted() method

Student.java

package net.bench.resources.sort.linkedlist;

public class Student {

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

	// constructors

	// getters & setters

	// toString()
}

SortLinkedListOfStudentsUsingStreamSorted.java

package net.bench.resources.sort.linkedlist;

import java.util.LinkedList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SortLinkedListOfStudentsUsingStreamSorted {

	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");
		students.forEach(System.out::println);


		// 2. sort using Stream - increasing-order of Age
		List<Student> sortedStudents = students
				.stream()
				.sorted(Comparator.comparingInt(Student::getAge))
				.collect(Collectors.toList());


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


		// 3. sort using Stream - reverse-order of Roll Id
		List<Student> reverseSortedStudents = students
				.stream()
				.sorted(Comparator.comparingInt(Student::getRollId).reversed())
				.collect(Collectors.toList());


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

Output:

1. Original LinkedList as per insertion-order :- 

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

2. Sorted Student LinkedList - according to Age :- 

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

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

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

2. List.sort() method

  • Sorts this list according to the order induced by the specified Comparator
  • All elements in this list must be mutually comparable using the specified comparator
  • That is, c.compare(e1, e1) must not throw a ClassCastException for any elements e1 and e2 in the list
  • If the specified comparator is null then all elements in this list must implement the Comparable interface and the elements’ natural ordering should be used
  • Method signature :- default void sort(Comparator<? super E> comparator)

2.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 Java 8 List’s sort() method

SortLinkedListOfIntegerUsingListSortMethod.java

package net.bench.resources.sort.linkedlist;

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

public class SortLinkedListOfIntegerUsingListSortMethod {

	public static void main(String[] args) {

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


		// 1.2 add integer numbers to AL
		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");
		numbers.forEach(System.out::println);


		// 2. List.sorted() - natural order
		numbers.sort(Comparator.naturalOrder());


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


		// 3. List.sorted() - reverse order
		numbers.sort(Comparator.reverseOrder());


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

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

2.2 Sorting LinkedList of String elements

  • A LinkedList contains String elements in insertion-order
  • We are sorting these String elements in alphabetical order using Java 8 List’s sort() method

SortLinkedListOfStringUsingListSortMethod.java

package net.bench.resources.sort.linkedlist;

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

public class SortLinkedListOfStringUsingListSortMethod {

	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");
		names.forEach(System.out::println);


		// 2. List.sort() - alphabetical order
		names.sort(Comparator.naturalOrder());


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


		// 3. List.sort() - reverse alphabetical order
		names.sort(Comparator.reverseOrder());


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

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.3 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 according to their age in natural order and their Id in descending order using Java 8 List’s sort() method

SortLinkedListOfStudentsUsingListSortMethod.java

package net.bench.resources.sort.linkedlist;

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

public class SortLinkedListOfStudentsUsingListSortMethod {

	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");
		students.forEach(System.out::println);


		// 2. List.sort() - increasing-order of Age
		students.sort(Comparator
				.comparing(Student::getAge));


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


		// 3. List.sort() - reverse-order of Roll Id
		students.sort(Comparator
				.comparingInt(Student::getRollId).reversed());


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

Output:

1. Original LinkedList as per insertion-order :- 

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

2. Sorted Student LinkedList - according to Age :- 

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

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

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

References:

Happy Coding !!
Happy Learning !!

Java 8 - How to sort LinkedHashSet using Stream
Java 8 – How to sort ArrayList using Stream