Java SortedSet

Java SortedSet

Overview

The SortedSet interface present in java.util package extends the Set interface present in the collection framework. It provides a total ordering of its elements. The elements are ordered using their natural ordering, or by a Comparator typically provided at sorted set creation time. This interface contains methods that extends from Set Interface.

SortedSet Hierarchy

In the above image, the navigable set extends the SortedSet interface. Since a Set doesn’t retain the insertion order, the navigable set interface provides the implementation to navigate through the Set. The class which implements the navigable set is a TreeSet which is an implementation of a self-balancing tree. Therefore, this interface provides us with a way to navigate through this tree.

Declaration

public interface SortedSet extends Set

Initialize SortedSet Objects

As SortedSet is an interface, objects cannot be created of the type SortedSet. We always need a class which extends this list in order to create an object. The type-safe can be defined as :

SortedSet<String> set = new TreeSet<String> ();

SortedSet Example

package com.techijournal.sets;

import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;

public class SortedSetExample {
	public static void main(String[] args) {
		SortedSet<String> ts = new TreeSet<String>();

		// using add()
		ts.add("Sumanth");
		ts.add("Durgesh");
		ts.add("Ritesh");

		// Adding the duplicate element
		ts.add("Durgesh");
		System.out.println(ts);

		// Removing items from TreeSet
		ts.remove("Ritesh");
		System.out.println("Set after removing Reitesh is : " + ts);

		// Iterating over Tree set items
		System.out.println("Iterating over set : ");
		Iterator<String> i = ts.iterator();
		while (i.hasNext()) {
			System.out.println(i.next());
		}
	}
}
Output :
[Durgesh, Ritesh, Sumanth]
Set after removing Reitesh is : [Durgesh, Sumanth]
Iterating over set : 
Durgesh
Sumanth

SortedSet Methods

METHODDESCRIPTION
add(element)This method is used to add a specific element to the set. The function adds the element only if the specified element is not already present in the set else the function returns False if the element is already present in the Set.
addAll(collection)This method is used to append all of the elements from the mentioned collection to the existing set. The elements are added randomly without following any specific order.
clear()This method is used to remove all the elements from the set but not delete the set. The reference for the set still exists.
comparator()This method returns the comparator used to order the elements in this set, or null if this set uses the natural ordering of its elements.
contains(element)This method is used to check whether a specific element is present in the Set or not.
containsAll(collection)This method is used to check whether the set contains all the elements present in the given collection or not. This method returns true if the set contains all the elements and returns false if any of the elements are missing.
first()This method returns the first(lowest) element present in this set.
hashCode()This method is used to get the hashCode value for this instance of the Set. It returns an integer value which is the hashCode value for this instance of the Set.
headSet(element)This method returns the elements which are less than the element that are present in the sorted set.
isEmpty()This method is used to check if a SortedSet is empty or not.
last()This method returns the last(highest) element present in the set.
remove(element)This method is used to remove the given element from the set. This method returns True if the specified element is present in the Set otherwise it returns False.
removeAll(collection)This method is used to remove all the elements from the collection which are present in the set. This method returns true if this set changed as a result of the call.
retainAll(collection)This method is used to retain all the elements from the set which are mentioned in the given collection. This method returns true if this set changed as a result of the call.
size()This method is used to get the size of the set. This returns an integer value which signifies the number of elements.
subSet(element1, element2)This method returns a sorted subset from the set containing the elements between element1 and element2.
tailSet(element)This method returns the elements which are greater than or equal to the element that are present in the sorted set.
toArray()This method is used to form an array of the same elements as that of the Set.

Various operations on SortedSet

All the elements of a SortedSet must implement the Comparable interface and all such elements must be mutually comparable. Mutually Comparable simply means that two objects accept each other as the argument to their compareTo method. The class which implements the SortedSet interface is TreeSet.

Adding Elements

In the examples we are using TreeSet as it implements SortedSet. It behaves like a simple set with the exception that it stores elements in a sorted format. TreeSet uses a tree data structure for storage. Let’s see how to create a sortedset object using this class.

package com.techijournal.sets;

import java.util.SortedSet;
import java.util.TreeSet;

public class SortedSetOperations {
	public static void main(String[] args) {
		SortedSet<String> ts = new TreeSet<String>();
		// Elements are added using add() method
		ts.add("Sumanth");
		ts.add("Durgesh");
		ts.add("Anjan");
		ts.add("Anil");
		System.out.println(ts);
	}
}
Output :
[Anil, Anjan, Durgesh, Sumanth]

Removing the Elements

The values can be removed from the SortedSet using the remove() method.

package com.techijournal.sets;

import java.util.SortedSet;
import java.util.TreeSet;

public class SortedSetOperations {
	public static void main(String[] args) {
		SortedSet<String> ts = new TreeSet<String>();
		// Elements are added using add() method
		ts.add("Sumanth");
		ts.add("Durgesh");
		ts.add("Anjan");
		ts.add("Anil");
		System.out.println("Initial TreeSet        " + ts);

		// Removing the element b
		ts.remove("Anjan");

		System.out.println("After removing element " + ts);
	}
}
Output : 
Initial TreeSet        [Anil, Anjan, Durgesh, Sumanth]
After removing element [Anil, Durgesh, Sumanth]

Iterating Elements

There are multiple ways to iterate through the SortedSet. One of the way is using enchanced for loop.

package com.techijournal.sets;

import java.util.SortedSet;
import java.util.TreeSet;

public class SortedSetOperations {
	public static void main(String[] args) {
		SortedSet<String> ts = new TreeSet<String>();
		// Elements are added using add() method
		ts.add("Sumanth");
		ts.add("Durgesh");
		ts.add("Anjan");
		ts.add("Anil");
		// Iterating though the SortedSet 
		for (String value : ts)
			System.out.print(value + ", ");
		System.out.println();
	}
}
Output : 
Anil, Anjan, Durgesh, Sumanth,

Conclusion

There is a lot more you can do with a SortedSet which will be discussed in further posts. A SortedSet is a Collection that cannot contain duplicate elements and implemented by other classes.

Thanks, Note

Thanks for spending your valuable time reading this post. Hope this post taught you something new today. Please share the post if you like it.

Sumanth Patnaikuni

Hi Guys. I am a technology enthusiast always try to learn new things. So I decided to share my knowledge through this platform. I worked for several companies and having 4+ years of experience. as full stack developer. Please leave your comments if there is any doubt regarding the blog. And also please recommend me if you require any particular topic so that I can guide you through my blog.

This Post Has 5 Comments

  1. 720p izle

    Pretty! This was a really wonderful post. Thank you for supplying this info. Carlina Alasdair Keung

  2. kristel haake

    I read a great article with pleasure, I hope it will continue

Leave a Reply