Using Java 8 Stream sorted() for Sorting Lists, Sets, and Maps
This tutorial demonstrates how to use Java 8 Stream's sorted() method to perform natural ordering, custom Comparator sorting, and reverse ordering on List, Set, and Map collections, including examples with lambda expressions and custom objects.
This article explains how to sort collections in Java 8 using the sorted() method of the Stream API. It covers natural ordering, custom Comparator sorting, and reverse ordering, and shows how to apply these techniques to List , Set , and Map objects.
sorted() method syntax
sorted() : sorts the stream elements in their natural order; the element class must implement Comparable .
sorted(Comparator<? super T> comparator) : sorts using a provided Comparator , which can be created with a lambda expression for ascending or descending order.
1. Sorting a List
list.stream().sorted()Reverse natural order:
list.stream().sorted(Comparator.reverseOrder())Sorting by a field using a Comparator:
list.stream().sorted(Comparator.comparing(Student::getAge))Reverse the Comparator order:
list.stream().sorted(Comparator.comparing(Student::getAge).reversed())Complete example (SortList.java):
package com.concretepage;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class SortList {
public static void main(String[] args) {
List
list = new ArrayList<>();
list.add(new Student(1, "Mahesh", 12));
list.add(new Student(2, "Suresh", 15));
list.add(new Student(3, "Nilesh", 10));
System.out.println("---Natural Sorting by Name---");
List
slist = list.stream().sorted().collect(Collectors.toList());
slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
System.out.println("---Natural Sorting by Name in reverse order---");
slist = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
System.out.println("---Sorting using Comparator by Age---");
slist = list.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
System.out.println("---Sorting using Comparator by Age with reverse order---");
slist = list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
}
}Student class (implements Comparable for natural ordering):
package com.concretepage;
public class Student implements Comparable
{
private int id;
private String name;
private int age;
public Student(int id, String name, int age) { this.id = id; this.name = name; this.age = age; }
public int getId() { return id; }
public String getName() { return name; }
public int getAge() { return age; }
@Override
public int compareTo(Student o) { return name.compareTo(o.getName()); }
// equals() and hashCode() omitted for brevity
}2. Sorting a Set
The Set must contain elements that correctly implement equals() and hashCode() . Natural ordering still requires Comparable .
package com.concretepage;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
public class SortSet {
public static void main(String[] args) {
Set
set = new HashSet<>();
set.add(new Student(1, "Mahesh", 12));
set.add(new Student(2, "Suresh", 15));
set.add(new Student(3, "Nilesh", 10));
System.out.println("---Natural Sorting by Name---");
set.stream().sorted().forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
System.out.println("---Natural Sorting by Name in reverse order---");
set.stream().sorted(Comparator.reverseOrder()).forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
System.out.println("---Sorting using Comparator by Age---");
set.stream().sorted(Comparator.comparing(Student::getAge)).forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
System.out.println("---Sorting using Comparator by Age in reverse order---");
set.stream().sorted(Comparator.comparing(Student::getAge).reversed()).forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
}
}3. Sorting a Map
Map entries can be sorted by key or by value. When the value is a custom object, the object must implement Comparable (or a Comparator must be supplied).
package com.concretepage;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
public class SortMap {
public static void main(String[] args) {
Map
map = new HashMap<>();
map.put(15, "Mahesh");
map.put(10, "Suresh");
map.put(30, "Nilesh");
System.out.println("---Sort by Map Value---");
map.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getValue))
.forEach(e -> System.out.println("Key: " + e.getKey() + ", Value: " + e.getValue()));
System.out.println("---Sort by Map Key---");
map.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getKey))
.forEach(e -> System.out.println("Key: " + e.getKey() + ", Value: " + e.getValue()));
}
}Sorting a map whose values are Student objects (by the student’s natural ordering, i.e., name):
package com.concretepage;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
public class SortMapOfCustomObject {
public static void main(String[] args) {
Map
map = new HashMap<>();
map.put(1, new Student(1, "Mahesh", 12));
map.put(2, new Student(2, "Suresh", 15));
map.put(3, new Student(3, "Nilesh", 10));
map.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getValue))
.forEach(e -> {
Integer key = e.getKey();
Student std = e.getValue();
System.out.println("Key: " + key + ", value: (" + std.getId() + ", " + std.getName() + ", " + std.getAge() + ")");
});
}
}All examples print the sorted results to the console, illustrating how the Stream API simplifies collection sorting in Java 8.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.