Java Sorted Set Example
In this example we shall show you how to make use ofJava Sorted Set.Java Sorted Set is aSet that further provides a total ordering on its elements. The elements are ordered using theirnatural ordering, or by aComparator typically provided at sorted set creation time.
All elements inserted into a sorted set must implement the Comparable interface (or be accepted by the specifiedComparator) and If you try to sort a set of elements which do not implement Comparable or not has a specificComparator, a ClassCastException will be thrown. Furthermore, all such elements must bemutually comparable(i.e, Mutually Comparable simply means that two objects accept each other as the argument to theircompareTo method)
1. Sorted Set Methods:
1.comparator()
Returns the comparator used to order the elements in this set, or null if this set uses the natural ordering of its elements.
2.first()
Returns the first (lowest) element currently in this set.
3.headSet(E toElement)
Returns a view of the portion of this set whose elements are strictly less than toElement.
4.last()
Returns the last (highest) element currently in this set.
5.subSet(E fromElement, E toElement)
Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive.
6.tailSet(E fromElement)
Returns a view of the portion of this set whose elements are greater than or equal tofromElement.
Now, Let’s suppose that your boss asks you to display the employees sorted by their age. The following example shows how to implement this case usingJava Sorted Set. Also, it will show some usage of the above methods.
2. Example:
2.1. Employee.java
package com.jcg.util.set;/** * @author ashraf_sarhan * */public class Employee implements Comparable {private String name;private int age;public Employee(String name, int age) {super();this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Override public int compareTo(Employee o) { //ascending order return this.age - o.getAge(); //descending order //return o.getAge() - this.age; }}Tip
java.lang.Comparable: int compareTo(Object o):
This method compares this object with o object. Returned int value has the following meanings.
positive– this object is greater than ozero– this object equals to onegative– this object is less than o
Also, we can use our own Comparator. If you need to know more about the Comparable and Comparator, Take a look onJava Comparable and Comparator Example to sort Objects byByron Kiourtzoglou
2.2. Sorter.java
package com.jcg.util.set;import java.util.Iterator;import java.util.SortedSet;import java.util.TreeSet;/** * @author ashraf_sarhan * */public class Sorter {public static void main(String[] args) {// TreeSet is an implementation of SortedSetSortedSet set = new TreeSet();set.add(new Employee("Ashraf", 60));set.add(new Employee("Sara", 50));set.add(new Employee("Mohamed", 10));set.add(new Employee("Esraa", 20));set.add(new Employee("Bahaa", 40));set.add(new Employee("Dalia", 30));// Iterating over the employees in the setSystem.out.println("Set after sorting:");Iterator it = set.iterator();while (it.hasNext()) {// Get employee name and ageEmployee epm = (Employee) it.next();System.out.println("Employee " + epm.getName() + ", his age: " + epm.getAge());}// Test comparator(), comparator will be null as we are using the Comparable interfaceSystem.out.println("Employee Set Comparator: " + set.comparator());// Test first()System.out.println("First Employee: " + set.first().getName());// Test last()System.out.println("Last Employee: " + set.last().getName());// Test headSet()System.out.println("headSet() result:");SortedSet headSet = set.headSet(new Employee("Dalia", 30));// Iterating over the employees in the headSetIterator headSetIt = headSet.iterator();while (headSetIt.hasNext()) {// Get employee name and ageEmployee epm = (Employee) headSetIt.next();System.out.println("Employee " + epm.getName() + " his age: " + epm.getAge());}// Test subSet()System.out.println("subSet() result:");SortedSet subSet = set.subSet(new Employee("Mohamed", 10), new Employee("Sara", 50));// Iterating over the employees in the subSetIterator subSetIt = subSet.iterator();while (subSetIt.hasNext()) {// Get employee name and ageEmployee epm = (Employee) subSetIt.next();System.out.println("Employee " + epm.getName() + " his age: " + epm.getAge());}// Test tailSet()System.out.println("tailSet() result:");SortedSet tailSet = set.tailSet(new Employee("Bahaa", 40));// Iterating over the employees in the tailSetIterator tailSetIt = tailSet.iterator();while (tailSetIt.hasNext()) {// Get employee name and ageEmployee epm = (Employee) tailSetIt.next();System.out.println("Employee " + epm.getName() + " his age: " + epm.getAge());}}}2.3. Explanation:
In the above example, we have theEmployee class which has two properties (name, age) and implements theComparable interface. Also, we have theSorter class that contains aSet of mutually comparable Employee objects. So, those objects were added to theSet in an unordered manner but take a look when we iterate over theSet, we got an ascending order of those objects based on the age property as we overridden thecompareTo method implementing the ascending ordering. Finally, we print the results of the Sorted Set methods listed above.
2.4. Output:
Set after sorting:Employee Mohamed, his age: 10Employee Esraa, his age: 20Employee Dalia, his age: 30Employee Bahaa, his age: 40Employee Sara, his age: 50Employee Ashraf, his age: 60Employee Set Comparator: nullFirst Employee: MohamedLast Employee: AshrafheadSet() result:Employee Mohamed his age: 10Employee Esraa his age: 20subSet() result:Employee Mohamed his age: 10Employee Esraa his age: 20Employee Dalia his age: 30Employee Bahaa his age: 40tailSet() result:Employee Bahaa his age: 40Employee Sara his age: 50Employee Ashraf his age: 60
3. Download the Source Code of this example:
This was an example of how to use Java Sorted Set.
You can download the full source code of this example here :Java Sorted Set Example Code

Thank you!
We will contact you soon.


