Java 8 – How to sort Set with stream.sorted()
In this quick tutorial, we’ll learn how to sort Set
in Java 8. stream.sorted()
is a predefined method of Stream
interface for sorting a Set
or any Collection
implemented classes.
Sorting the elements of Set
is similar to the sorting of the list.
1. Natural/Default Sorting Order
In this, we have a Set
of employees and the type of the set is String.
package org.websparrow.sorting;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
public class SetSorting {
public static void main(String[] args) {
Set<String> employees = new HashSet<>();
employees.add("Sunny Tiwari");
employees.add("Ashutosh Pandey");
employees.add("Vipin Singh");
employees.add("Mintoo Prasad");
System.out.println("--- Set before sorted ---");
employees.forEach(System.out::println);
System.out.println("--- Set after sorted ---");
employees.stream().sorted().forEach(System.out::println);
}
}
Output
--- Set before sorted ---
Vipin Singh
Ashutosh Pandey
Mintoo Prasad
Sunny Tiwari
--- Set after sorted ---
Ashutosh Pandey
Mintoo Prasad
Sunny Tiwari
Vipin Singh
Alternately, we can also pass the Comparator.naturalOrder()
as argument in overloaded sorted()
method i.e. sorted(Comparator.naturalOrder())
which gives the same output.
employees
.stream()
.sorted(Comparator.naturalOrder())
.forEach(System.out::println);
Similarly, we can also compare the elements one by one by calling compareTo(String object)
method as we do in the older version of Java. And it also produces the same output.
employees
.stream()
.sorted((o1, o2) -> o1.compareTo(o2))
.forEach(System.out::println);
2. Sorting in Reverse Order
The Set
elements can be sorted in revered order by passing the Comparator.naturalOrder()
. It returns a comparator that imposes the reverse of the natural ordering.
package org.websparrow.sorting;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
public class SetSortingReverseOrder {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("Sunny Tiwari");
set.add("Ashutosh Pandey");
set.add("Vipin Singh");
set.add("Mintoo Prasad");
System.out.println("--- Set before sorted ---");
set.forEach(System.out::println);
System.out.println("--- Set after sorted (Reverse order) ---");
set.stream().sorted(Comparator.reverseOrder())
.forEach(System.out::println);
System.out.println("--- Set after sorted (Reverse order) Old days ---");
set.stream().sorted((o1, o2) -> o2.compareTo(o1))
.forEach(System.out::println);
}
}
Output
--- Set before sorted ---
Vipin Singh
Ashutosh Pandey
Mintoo Prasad
Sunny Tiwari
--- Set after sorted (Reverse order) ---
Vipin Singh
Sunny Tiwari
Mintoo Prasad
Ashutosh Pandey
--- Set after sorted (Reverse order) Old days ---
Vipin Singh
Sunny Tiwari
Mintoo Prasad
Ashutosh Pandey
3. Sorting Set of Custom Object
We can also sort custom object Set
by using stream.sorted()
method. Let’s we have Car
class along with its attributes like id, brand name, model year, etc.
package org.websparrow.sorting;
public class Car {
// Generate Getters and Setters...
private int id;
private String brand;
private int modelYear;
public Car(int id, String brand, int modelYear) {
this.id = id;
this.brand = brand;
this.modelYear = modelYear;
}
@Override
public String toString() {
return "Car [id=" + id + ", brand=" + brand + ", modelYear=" + modelYear
+ "]";
}
}
3.1 Sort by id (Natural/Default Sort Order)
package org.websparrow.sorting;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
public class SetSortingCustomObject {
public static void main(String[] args) {
Set<Car> set = new HashSet<>();
set.add(new Car(166, "Tata", 1967));
set.add(new Car(112, "Mahindra", 1978));
set.add(new Car(66, "Hindustan Motors", 1950));
set.add(new Car(203, "BMW", 1998));
System.out.println("--- Cars before sorted ---");
set.forEach(System.out::println);
System.out.println("--- Cars after sorted ---");
set.stream().sorted(Comparator.comparingInt(Car::getId))
.forEach(System.out::println);
System.out.println("--- Cars after sorted (Old days) ---");
set.stream().sorted((o1, o2) -> o1.getId() - o2.getId())
.forEach(System.out::println);
}
}
Output
--- Cars before sorted ---
Car [id=166, brand=Tata, modelYear=1967]
Car [id=112, brand=Mahindra, modelYear=1978]
Car [id=66, brand=Hindustan Motors, modelYear=1950]
Car [id=203, brand=BMW, modelYear=1998]
--- Cars after sorted ---
Car [id=66, brand=Hindustan Motors, modelYear=1950]
Car [id=112, brand=Mahindra, modelYear=1978]
Car [id=166, brand=Tata, modelYear=1967]
Car [id=203, brand=BMW, modelYear=1998]
--- Cars after sorted (Old days) ---
Car [id=66, brand=Hindustan Motors, modelYear=1950]
Car [id=112, brand=Mahindra, modelYear=1978]
Car [id=166, brand=Tata, modelYear=1967]
Car [id=203, brand=BMW, modelYear=1998]
3.2 Sort by id (Reverse Order)
Comparator
‘s reversed()
method is used to reveres the elements of a sorted Set.
package org.websparrow.sorting;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
public class SetSortingCustomObject {
public static void main(String[] args) {
Set<Car> set = new HashSet<>();
set.add(new Car(166, "Tata", 1967));
set.add(new Car(112, "Mahindra", 1978));
set.add(new Car(66, "Hindustan Motors", 1950));
set.add(new Car(203, "BMW", 1998));
System.out.println("--- Cars before sorted ---");
set.forEach(System.out::println);
System.out.println("--- Cars after sorted (Reverse order)---");
set.stream().sorted(Comparator.comparingInt(Car::getId).reversed())
.forEach(System.out::println);
System.out.println("--- Cars after sorted (Reverse order) Old days ---");
set.stream().sorted((o1, o2) -> o2.getId() - o1.getId())
.forEach(System.out::println);
}
}
Output
--- Cars before sorted ---
Car [id=166, brand=Tata, modelYear=1967]
Car [id=112, brand=Mahindra, modelYear=1978]
Car [id=66, brand=Hindustan Motors, modelYear=1950]
Car [id=203, brand=BMW, modelYear=1998]
--- Cars after sorted (Reverse order)---
Car [id=203, brand=BMW, modelYear=1998]
Car [id=166, brand=Tata, modelYear=1967]
Car [id=112, brand=Mahindra, modelYear=1978]
Car [id=66, brand=Hindustan Motors, modelYear=1950]
--- Cars after sorted (Reverse order) Old days ---
Car [id=203, brand=BMW, modelYear=1998]
Car [id=166, brand=Tata, modelYear=1967]
Car [id=112, brand=Mahindra, modelYear=1978]
Car [id=66, brand=Hindustan Motors, modelYear=1950]
3.3 Sort by brand
Similarly, we can also sort Car
by its brand name.
System.out.println("--- Cars after sorted ---");
set.stream().sorted(Comparator.comparing(Car::getBrand))
.forEach(System.out::println);
System.out.println("--- Cars after sorted Old days ---");
set.stream().sorted((o1, o2) -> o1.getBrand().compareTo(o2.getBrand()))
.forEach(System.out::println);
3.4 Sort by brand (Reverse Order)
System.out.println("--- Cars after sorted (Reverse order)---");
set.stream().sorted(Comparator.comparing(Car::getBrand).reversed())
.forEach(System.out::println);
System.out.println("--- Cars after sorted (Reverse order) Old days ---");
set.stream().sorted((o1, o2) -> o2.getBrand().compareTo(o1.getBrand()))
.forEach(System.out::println);
References
- Interface Stream<T>
- Stream<T> sorted()
- Stream<T> sorted(Comparator<? super T> comparator)
- Interface Comparator<T>