Java 8 – How to sort ArrayList using Stream

In this article we will discuss different ways to sort ArrayList 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 ArrayList of Integer numbers

  • An ArrayList contains integers numbers in random order
  • We are sorting these integer numbers in natural order (or ascending order) using Java 8 Stream’s sorted() method

SortArrayListOfIntegerUsingStream.java

package net.bench.resources.sort.arraylist;

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

public class SortArrayListOfIntegerUsingStream {

	public static void main(String[] args) {

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


		// 1.2 add integer numbers to AL
		numbers.add(86);
		numbers.add(19);
		numbers.add(97);
		numbers.add(63);
		numbers.add(23);
		numbers.add(92);
		numbers.add(94);


		// 1.3 original ArrayList in insertion order
		System.out.println("1. Original ArrayList<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 "
				+ "ArrayList<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 "
				+ "ArrayList<Integer> :- \n");
		reverseSortedNumber.forEach(System.out::println);
	}
}

Output:

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

86
19
97
63
23
92
94

2. Natural order of ArrayList<Integer> :- 

19
23
63
86
92
94
97

3. Reverse order of ArrayList<Integer> :- 

97
94
92
86
63
23
19

1.2 Sorting ArrayList of String elements

  • An ArrayList contains String elements in random order
  • We are sorting these String elements in alphabetical order using Java 8 Stream’s sorted() method

SortArrayListOfStringUsingStream.java

package net.bench.resources.sort.arraylist;

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

public class SortArrayListOfStringUsingStream {

	public static void main(String[] args) {

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

		// 1.1 add names to AL
		names.add("Rambha");
		names.add("Amala");
		names.add("Urvashi");
		names.add("Meghana");
		names.add("Pavithra");
		names.add("Sneha");


		// 1.2 original ArrayList in insertion order
		System.out.println("1. Original ArrayList<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 ArrayList<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 ArrayList<String> :- \n");
		reverseSortedNames.forEach(System.out::println);
	}
}

Output:

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

Rambha
Amala
Urvashi
Meghana
Pavithra
Sneha

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

Amala
Meghana
Pavithra
Rambha
Sneha
Urvashi

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

Urvashi
Sneha
Rambha
Pavithra
Meghana
Amala

1.3 Sorting ArrayList of Students objects

  • An ArrayList contains Student objects with attributes such as Id, name and their age in random order
  • We are sorting these Student objects according to their age in natural order 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()
}

SortArrayListOfStudentsUsingStreamSorted.java

package net.bench.resources.sort.arraylist;

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

public class SortArrayListOfStudentsUsingStreamSorted {

	public static void main(String[] args) {

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


		// 1.1 add Students to AL
		students.add(new Student(101, "Rambha", 46));
		students.add(new Student(102, "Amala", 57));
		students.add(new Student(103, "Urvashi", 49));
		students.add(new Student(104, "Meghana", 24));
		students.add(new Student(105, "Pavithra", 29));
		students.add(new Student(106, "Sneha", 38));


		// 1.2 original ArrayList in insertion order
		System.out.println("1. Original ArrayList "
				+ "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 ArrayList -"
				+ " 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 ArrayList -"
				+ " according to Id :- \n");
		reverseSortedStudents.forEach(System.out::println);
	}
}

Output:

1. Original ArrayList as per insertion-order :- 

Student [rollNumber=101, name=Rambha, age=46]
Student [rollNumber=102, name=Amala, age=57]
Student [rollNumber=103, name=Urvashi, age=49]
Student [rollNumber=104, name=Meghana, age=24]
Student [rollNumber=105, name=Pavithra, age=29]
Student [rollNumber=106, name=Sneha, age=38]

2. Sorted Student ArrayList - according to Age :- 

Student [rollNumber=104, name=Meghana, age=24]
Student [rollNumber=105, name=Pavithra, age=29]
Student [rollNumber=106, name=Sneha, age=38]
Student [rollNumber=101, name=Rambha, age=46]
Student [rollNumber=103, name=Urvashi, age=49]
Student [rollNumber=102, name=Amala, age=57]

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

Student [rollNumber=106, name=Sneha, age=38]
Student [rollNumber=105, name=Pavithra, age=29]
Student [rollNumber=104, name=Meghana, age=24]
Student [rollNumber=103, name=Urvashi, age=49]
Student [rollNumber=102, name=Amala, age=57]
Student [rollNumber=101, name=Rambha, age=46]

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 ArrayList of Integer numbers

  • An ArrayList contains integers numbers in random order
  • We are sorting these integer numbers in natural order (or ascending order) using Java 8 List’s sort() method

SortArrayListOfIntegerUsingListSortMethod.java

package net.bench.resources.sort.arraylist;

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

public class SortArrayListOfIntegerUsingListSortMethod {

	public static void main(String[] args) {

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


		// 1.2 add integer numbers to AL
		numbers.add(86);
		numbers.add(19);
		numbers.add(97);
		numbers.add(63);
		numbers.add(23);
		numbers.add(92);
		numbers.add(94);


		// 1.3 original ArrayList in insertion order
		System.out.println("1. Original ArrayList<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 "
				+ "ArrayList<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 "
				+ "ArrayList<Integer> :- \n");
		numbers.forEach(System.out::println);
	}
}

Output:

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

86
19
97
63
23
92
94

2. Natural order of ArrayList<Integer> :- 

19
23
63
86
92
94
97

3. Reverse order of ArrayList<Integer> :- 

97
94
92
86
63
23
19

2.2 Sorting ArrayList of String elements

  • An ArrayList contains String elements in random order
  • We are sorting these String elements in alphabetical order using Java 8 List’s sort() method

SortArrayListOfStringUsingListSortMethod.java

package net.bench.resources.sort.arraylist;

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

public class SortArrayListOfStringUsingListSortMethod {

	public static void main(String[] args) {

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

		// 1.1 add names to AL
		names.add("Ramki");
		names.add("Abbas");
		names.add("Ulaganayagan");
		names.add("Mohanlal");
		names.add("PrithiviRaj");
		names.add("Surya");


		// 1.2 original ArrayList as per insertion order
		System.out.println("1. Original ArrayList<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 ArrayList<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 ArrayList<String> :- \n");
		names.forEach(System.out::println);
	}
}

Output:

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

Ramki
Abbas
Ulaganayagan
Mohanlal
PrithiviRaj
Surya

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

Abbas
Mohanlal
PrithiviRaj
Ramki
Surya
Ulaganayagan

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

Ulaganayagan
Surya
Ramki
PrithiviRaj
Mohanlal
Abbas

2.3 Sorting ArrayList of Students objects

  • An ArrayList contains Student objects with attributes such as Id, name and their age in random 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

SortArrayListOfStudentsUsingListSortMethod.java

package net.bench.resources.sort.arraylist;

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

public class SortArrayListOfStudentsUsingListSortMethod {

	public static void main(String[] args) {

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


		// 1.1 add Students to AL
		students.add(new Student(101, "Rambha", 46));
		students.add(new Student(102, "Amala", 57));
		students.add(new Student(103, "Urvashi", 49));
		students.add(new Student(104, "Meghana", 24));
		students.add(new Student(105, "Pavithra", 29));
		students.add(new Student(106, "Sneha", 38));


		// 1.2 original ArrayList in insertion order
		System.out.println("1. Original ArrayList "
				+ "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 ArrayList -"
				+ " 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 ArrayList -"
				+ " according to Id :- \n");
		students.forEach(System.out::println);
	}
}

Output:

1. Original ArrayList as per insertion-order :- 

Student [rollNumber=101, name=Rambha, age=46]
Student [rollNumber=102, name=Amala, age=57]
Student [rollNumber=103, name=Urvashi, age=49]
Student [rollNumber=104, name=Meghana, age=24]
Student [rollNumber=105, name=Pavithra, age=29]
Student [rollNumber=106, name=Sneha, age=38]

2. Sorted Student ArrayList - according to Age :- 

Student [rollNumber=104, name=Meghana, age=24]
Student [rollNumber=105, name=Pavithra, age=29]
Student [rollNumber=106, name=Sneha, age=38]
Student [rollNumber=101, name=Rambha, age=46]
Student [rollNumber=103, name=Urvashi, age=49]
Student [rollNumber=102, name=Amala, age=57]

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

Student [rollNumber=106, name=Sneha, age=38]
Student [rollNumber=105, name=Pavithra, age=29]
Student [rollNumber=104, name=Meghana, age=24]
Student [rollNumber=103, name=Urvashi, age=49]
Student [rollNumber=102, name=Amala, age=57]
Student [rollNumber=101, name=Rambha, age=46]

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to sort LinkedList using Stream
Java 8 - How to remove duplicates from LinkedList