Ashraf Sarhan

About Ashraf Sarhan

Ashraf Sarhan is a passionate software engineer, an open source enthusiast, has a Bsc. degree in Computer and Information Systems from Alexandria University. He is experienced in building large, scalable and distributed enterprise applications/service in multiple domains. He also has a keen interest in JavaEE, SOA, Agile and Big Data technologies.

Java Sorted Set Example

In this example we shall show you how to make use of Java Sorted Set.
Java Sorted Set is a Set that further provides a total ordering on its elements. The elements are ordered using their natural ordering, or by a Comparator typically provided at sorted set creation time.

All elements inserted into a sorted set must implement the Comparable interface (or be accepted by the specified Comparator) and If you try to sort a set of elements which do not implement Comparable or not has a specific Comparator, a ClassCastException will be thrown. Furthermore, all such elements must be mutually comparable (i.e, Mutually Comparable simply means that two objects accept each other as the argument to their compareTo 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 to fromElement.

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 using Java 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.

  1. positive – this object is greater than o
  2. zero – this object equals to o
  3. negative – 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 on Java Comparable and Comparator Example to sort Objects by Byron 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 SortedSet
		SortedSet 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 set
		System.out.println("Set after sorting:");
		Iterator it = set.iterator();
		while (it.hasNext()) {
			// Get employee name and age
			Employee 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 interface
		System.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 headSet
		Iterator headSetIt = headSet.iterator();
		while (headSetIt.hasNext()) {
			// Get employee name and age
			Employee 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 subSet
		Iterator subSetIt = subSet.iterator();
		while (subSetIt.hasNext()) {
			// Get employee name and age
			Employee 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 tailSet
		Iterator tailSetIt = tailSet.iterator();
		while (tailSetIt.hasNext()) {
			// Get employee name and age
			Employee epm = (Employee) tailSetIt.next();
			System.out.println("Employee " + epm.getName() + " his age: " + epm.getAge());
		}

	}

}

2.3. Explanation:

In the above example, we have the Employee class which has two properties (name, age) and implements the Comparable interface. Also, we have the Sorter class that contains a Set of mutually comparable Employee objects. So, those objects were added to the Set in an unordered manner but take a look when we iterate over the Set, we got an ascending order of those objects based on the age property as we overridden the compareTo 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: 10
Employee Esraa, his age: 20
Employee Dalia, his age: 30
Employee Bahaa, his age: 40
Employee Sara, his age: 50
Employee Ashraf, his age: 60

Employee Set Comparator: null

First Employee: Mohamed

Last Employee: Ashraf

headSet() result:
Employee Mohamed his age: 10
Employee Esraa his age: 20

subSet() result:
Employee Mohamed his age: 10
Employee Esraa his age: 20
Employee Dalia his age: 30
Employee Bahaa his age: 40

tailSet() result:
Employee Bahaa his age: 40
Employee Sara his age: 50
Employee Ashraf his age: 60

3. Download the Source Code of this example:

This was an example of how to use Java Sorted Set.

Download
You can download the full source code of this example here : Java Sorted Set Example Code

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close