In this article, we will discuss how to sort TreeSet elements in descending order using Java 8 Stream API
Before proceeding with this sorting examples understand below items,
- What is Set ?
- What is HashSet ?
- What is TreeSet ?
- Iterating and printing Set elements
- Iterating Treeset
- How to sort TreeSet in descending order – before Java 8
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 TreeSet of Integer numbers
- A TreeSet contains integer numbers in natural order ( or ascending order)
- We are sorting these integer numbers in descending order using Java 8 Stream’s sorted() method
SortTreeSetOfIntegerInDescUsingStream.java
package net.bench.resources.sort.treeset;
import java.util.Comparator;
import java.util.TreeSet;
import java.util.Set;
public class SortTreeSetOfIntegerInDescUsingStream {
public static void main(String[] args) {
// 1. create TreeSet
Set<Integer> numbers = new TreeSet<>();
// 1.2 add integer numbers to TS
numbers.add(181);
numbers.add(219);
numbers.add(529);
numbers.add(761);
numbers.add(431);
numbers.add(671);
numbers.add(351);
// 1.3 original TreeSet in insertion order
System.out.println("1. Original TreeSet<Integer> in ASC order :- \n");
numbers.forEach(System.out::println);
// 2. Reverse Order
System.out.println("\n2. TreeSet<Integer> in DESC order :- \n");
// 2.1 reverse order - Stream.sorted() and print
numbers
.stream() // get sequential stream
.sorted(Comparator.reverseOrder()) // reverse order sorting
.forEach(System.out::println); // print
}
}
Output:
1. Original TreeSet<Integer> in ASC order :-
181
219
351
431
529
671
761
2. TreeSet<Integer> in DESC order :-
761
671
529
431
351
219
181
1.2 Sorting TreeSet of String elements
- A TreeSet contains String elements in alphabetical order ( or ascending order)
- We are sorting these String elements in reverse alphabetical order using Java 8 Stream’s sorted() method
SortTreeSetOfStringInDescUsingStream.java
package net.bench.resources.sort.treeset;
import java.util.Comparator;
import java.util.TreeSet;
import java.util.Set;
public class SortTreeSetOfStringInDescUsingStream {
public static void main(String[] args) {
// 1. create TreeSet
Set<String> names = new TreeSet<>();
// 1.1 add names to TS
names.add("Saranya");
names.add("Karthika");
names.add("Amudha");
names.add("Pushpa");
names.add("Bhagyalakshmi");
names.add("Meena");
// 1.2 original TreeSet in insertion order
System.out.println("1. Original TreeSet<String> "
+ "in alphabetical order :- \n");
names.forEach(System.out::println);
// 2. Sorting Reverse Alphabetical order
System.out.println("\n2. TreeSet<String> "
+ "in reverse alphabetical order :- \n");
// 2.1 sort using Stream - reverse alphabetical order
names
.stream() // get sequential stream
.sorted(Comparator.reverseOrder()) // reverse alphabetical sorting
.forEach(System.out::println); // print
}
}
Output:
1. Original TreeSet<String> in alphabetical order :-
Amudha
Bhagyalakshmi
Karthika
Meena
Pushpa
Saranya
2. TreeSet<String> in reverse alphabetical order :-
Saranya
Pushpa
Meena
Karthika
Bhagyalakshmi
Amudha
1.3 Sorting TreeSet of Employee objects
- A TreeSet contains Employee objects with attributes such as Id, name and their salary in ascending order of their Id‘s
- We are sorting these Employee objects in descending order according to their salary using Java 8 Stream’s sorted() method
Employee.java
package net.bench.resources.sort.treeset;
public class Employee implements Comparable<Employee> {
// member variables
private int id;
private String name;
private long salary;
// 3-arg parameterized constructor
// getters and setters
// toString()
// compareTo
@Override
public int compareTo(Employee emp) {
return Long.compare(this.getId(), emp.getId());
}
}
SortLinkedHashSetOfEmployeesUsingStreamSorted.java
package net.bench.resources.sort.treeset;
import java.util.Comparator;
import java.util.TreeSet;
import java.util.Set;
public class SortTreeSetOfEmployeesInDescUsingStreamSorted {
public static void main(String[] args) {
// 1. create TreeSet
Set<Employee> employees = new TreeSet<>();
// 1.1 add Employees to TS
employees.add(new Employee(101, "Saranya", 85000L));
employees.add(new Employee(102, "ThenMozhi", 57000L));
employees.add(new Employee(103, "Amudha", 49000L));
employees.add(new Employee(104, "Pushpa", 24000L));
employees.add(new Employee(105, "Bhagyalakshmi", 29000L));
employees.add(new Employee(106, "Meena", 38000L));
// 1.2 original TreeSet in insertion order
System.out.println("1. Original TreeSet "
+ "as per sorted-order of Id :- \n");
employees.forEach(System.out::println);
// 2. Sorting Employee - decreasing salary
System.out.println("\n2. Sorted Employee TreeSet - "
+ "according to decreasing salary :- \n");
// 2.1 sort using Stream - decreasing-order of salary
employees
.stream()
.sorted(Comparator.comparingLong(Employee::getSalary).reversed())
.forEach(System.out::println);
}
}
Output:
1. Original TreeSet as per sorted-order of Id :-
Employee [id=101, name=Saranya, salary=85000]
Employee [id=102, name=ThenMozhi, salary=57000]
Employee [id=103, name=Amudha, salary=49000]
Employee [id=104, name=Pushpa, salary=24000]
Employee [id=105, name=Bhagyalakshmi, salary=29000]
Employee [id=106, name=Meena, salary=38000]
2. Sorted Employee TreeSet - according to decreasing salary :-
Employee [id=101, name=Saranya, salary=85000]
Employee [id=102, name=ThenMozhi, salary=57000]
Employee [id=103, name=Amudha, salary=49000]
Employee [id=106, name=Meena, salary=38000]
Employee [id=105, name=Bhagyalakshmi, salary=29000]
Employee [id=104, name=Pushpa, salary=24000]
Related Articles:
- Java 8 – How to sort ArrayList elements
- Java 8 – Sorting List of primitive, String & Custom Objects
- Java 8 – Sorting ArrayList using sort() method of List
- Java 8 – How to sort LinkedList elements
- Java 8 – How to sort HashSet elements
- Java 8 – How to sort LinkedHashSet elements
- Java 8 – How to sort TreeSet in descending order
- Java 8 – How to sort List and Arrays with null values present
- Java 8 – How to sort Arrays in Ascending and Descending order ?
- Java 8 – Sorting list of objects on multiple fields (3-level attributes)
References:
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#sorted–
- https://docs.oracle.com/javase/8/docs/api/java/util/List.html
- https://docs.oracle.com/javase/8/docs/api/java/util/List.html#sort-java.util.Comparator-
Happy Coding !!
Happy Learning !!