SortedSet Interface in Java
The SortedSet interface present in java.util package extends the Set interface present in
the collection framework. It is an interface that implements the mathematical set
the navigable set extends the sorted set interface. Since a set doesn’t retain the insertion order,
the navigable set interface provides the implementation to navigate through the Set
The SortedSet interface is declared as:
public interface SortedSet extends Set
All the elements of a SortedSet must implement the Comparable interface (or be accepted by the
specified Comparator) 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. t behaves like a simple set with
the exception that it stores elements in a sorted format. TreeSet uses a tree data structure for
storage. Objects are stored in sorted, ascending order.
Various Operations on SortedSet
Adding Elements: use the add() method. the insertion order is not retained in the TreeSet.
Internally, for every element, the values are compared and sorted in the ascending order. So that
null values and duplicate values are not accepted.
Accessing the Elements: contains(), first(), last(),
Removing the Values: using the remove() method.
Iterating through the SortedSet: use the enhanced for loop.
Methods
comparator() Returns the comparator which is used to order the elements in the
given set. Also returns null if the given set uses the natural ordering
of the element.
first() Returns the first element from the current set.
headSet(E toElement) Returns a view of the portion of the given set whose elements are
strictly less than the toElement.
last() Returns the reverse order view of the mapping which present in the
map.
spliterator() Returns a key-value mapping which is associated with the least key
in the given map. Also, returns null if the map is empty.
subSet(E fromElement, Returns a key-value mapping which is associated with the greatest
E toElement) key which is less than or equal to the given key. Also, returns null if
the map is empty.
tailSet(E fromElement) Returns a view of the map whose keys are strictly less than the
toKey.
Example:
import java.util.*;
class Test{
public static void main(String[] args)
{
SortedSet<String> ts = new TreeSet<String>();
ts.add("A");
ts.add("B");
ts.add("C");
ts.add("A");
System.out.println(ts);
String check = "D";
System.out.println(check + " " + ts.contains(check));
System.out.println("First Value " + ts.first());
System.out.println("First Value " + ts.last());
System.out.println("First Value " + ts.remove(“B”));
for (String value : ts) {
System.out.print(value + ", "); }
System.out.println();
}
}
Navigable Set
The NavigableSet interface inherits from the SortedSet interface. It behaves like a SortedSet with
the exception that we have navigation methods available in addition to the sorting mechanisms of
the SortedSet.
The classes that implement this interface are, TreeSet and ConcurrentSkipListSet
It provide method for navigating the set in both forward and backward direction
METHOD DESCRIPTION
Returns the least element in this set greater than or equal to the
ceiling?(E e)
given element, or null if there is no such element.
Returns an iterator over the elements in this set, in descending
descendingIterator()
order.
descendingSet() Returns a reverse order view of the elements contained in this set.
Returns the greatest element in this set less than or equal to the
floor?(E e)
given element, or null if there is no such element.
Returns a view of the portion of this set whose elements are
headSet?(E toElement)
strictly less than toElement.
headSet?(E toElement, boolean Returns a view of the portion of this set whose elements are less
inclusive) than (or equal to, if inclusive is true) toElement.
Returns the least element in this set strictly greater than the given
higher?(E e)
element, or null if there is no such element.
Returns an iterator over the elements in this set, in ascending
iterator()
order.
Returns the greatest element in this set strictly less than the given
lower?(E e)
element, or null if there is no such element.
METHOD DESCRIPTION
Retrieves and removes the first (lowest) element, or returns null if
pollFirst()
this set is empty.
Retrieves and removes the last (highest) element, or returns null if
pollLast()
this set is empty.
subSet?(E fromElement, boolean Returns a view of the portion of this set whose elements range
fromInclusive, E toElement, from fromElement to toElement.
boolean toInclusive)
subSet?(E fromElement, E Returns a view of the portion of this set whose elements range
toElement) from fromElement, inclusive, to toElement, exclusive.
Returns a view of the portion of this set whose elements are
tailSet?(E fromElement)
greater than or equal to fromElement.
tailSet?(E fromElement, boolean Returns a view of the portion of this set whose elements are
inclusive) greater than (or equal to, if inclusive is true) fromElement.
Example
import java.util.*;
//NavigableSetExample
public class Main {
public static void main(String[] args) {
// Create a new TreeSet
NavigableSet treeSet = new TreeSet<>();
// Add some elements to the set
treeSet.add(10);
treeSet.add(20);
treeSet.add(30);
treeSet.add(40);
// Use NavigableSet methods to navigate the set
System.out.println("Floor of 25: " + treeSet.floor(25));
System.out.println("Ceiling of 35: " + treeSet.ceiling(35));
System.out.println("Lower of 25: " + treeSet.lower(25));
System.out.println("Higher of 35: " + treeSet.higher(35));
System.out.println("First element: " + treeSet.first());
System.out.println("Last element: " + treeSet.last());
System.out.println("Subset between 15 and 35: " + treeSet.subSet(15, true, 35, true));
System.out.println("Head set with 30: " + treeSet.headSet(30, true));
System.out.println("Tail set with 20: " + treeSet.tailSet(20, true));
System.out.println("Descending order: " + treeSet.descendingSet());
// Remove an element from the set
treeSet.remove(20);
// Check if an element exists in the set
System.out.println("Contains 20: " + treeSet.contains(20));
// Clear the set
treeSet.clear();
}
}
Example 2
import java.util.NavigableSet;
import java.util.TreeSet;
public class NavigableSetDemo
{
public static void main(String[] args)
{
NavigableSet<Integer> ns = new TreeSet<>();
ns.add(0);
ns.add(1);
ns.add(2);
ns.add(3);
ns.add(4);
ns.add(5);
ns.add(6);
// Get a reverse view of the navigable set
NavigableSet<Integer> reverseNs = ns.descendingSet();
// Print the normal and reverse views
System.out.println("Normal order: " + ns);
System.out.println("Reverse order: " + reverseNs);
NavigableSet<Integer> threeOrMore = ns.tailSet(3, true);
System.out.println("3 or more: " + threeOrMore);
System.out.println("lower(3): " + ns.lower(3));
System.out.println("floor(3): " + ns.floor(3));
System.out.println("higher(3): " + ns.higher(3));
System.out.println("ceiling(3): " + ns.ceiling(3));
System.out.println("pollFirst(): " + ns.pollFirst());
System.out.println("Navigable Set: " + ns);
System.out.println("pollLast(): " + ns.pollLast());
System.out.println("Navigable Set: " + ns);
System.out.println("pollFirst(): " + ns.pollFirst());
System.out.println("Navigable Set: " + ns);
System.out.println("pollFirst(): " + ns.pollFirst());
System.out.println("Navigable Set: " + ns);
System.out.println("pollFirst(): " + ns.pollFirst());
System.out.println("Navigable Set: " + ns);
System.out.println("pollFirst(): " + ns.pollFirst());
System.out.println("pollLast(): " + ns.pollLast());
}
}
Constructor Of HashSet Class
1. HashSet()
HashSet<E> hs = new HashSet<E>();
2.HashSet(int initialCapacity, float loadFactor)
HashSet<E> hs = new HashSet<E>(int initialCapacity, float loadFactor);
3. HashSet(int initialCapacity)
HashSet<E> hs = new HashSet<E>(int initialCapacity);
4. HashSet(Collection)
this constructor is used when any conversion is needed from any Collection object to the HashSet object.
HashSet<E> hs = new HashSet<E>(Collection C);
Methods in HashSet
Method Description
Used to add the specified element if it is not present, if it is present then
add(E e)
return false.
clear() Used to remove all the elements from the set.
contains(Object o) Used to return true if an element is present in a set.
remove(Object o) Used to remove the element if it is present in set.
iterator() Used to return an iterator over the element in the set.
Used to check whether the set is empty or not. Returns true for empty and
isEmpty()
false for a non-empty condition for set.
size() Used to return the size of the set.
Method Description
clone() Used to create a shallow copy of the set.
Used to verify the equality of an Object with a HashSet and compare them.
equals() The list returns true only if both HashSet contains the same elements,
irrespective of order.
hashcode() Returns the hash code value for this set.
This method is used to remove all the elements from the collection which are
removeAll(collection) present in the set. This method returns true if this set changes as a result of
the call.
Example
import java.util.HashSet;
public class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
@Override
public String toString() {
return title " by " author;
}
public static void main(String[] args) {
HashSet<Book> bookSet = new HashSet<>();
Book book1 = new Book("The Great Gatsby", "F. Scott Fitzgerald");
Book book2 = new Book("To Kill a Mockingbird", "Harper Lee");
Book book3 = new Book("1984", "George Orwell");
bookSet.add(book1);
bookSet.add(book2);
bookSet.add(book3);
System.out.println("HashSet: " bookSet);
System.out.println("Size: " bookSet.size());
Book bookToRemove = new Book("1984", "George Orwell");
bookSet.remove(bookToRemove);
System.out.println("After removal: " bookSet);
}
}
LinkedHash Set
Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set interface. It inherits the
HashSet class and implements the Set interface.
LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements.
When the iteration order is needed to be maintained this class is used.
. When cycling through LinkedHashSet using an iterator, the elements will be returned in the order in which
they were inserted.
Properties of LinkedHashset
o Java LinkedHashSet class contains unique elements only like HashSet.
o Java LinkedHashSet class provides all optional set operations and permits null elements.
o Java LinkedHashSet class is non-synchronized.
o Java LinkedHashSet class maintains insertion order.
Constructors of LinkedHashSet Class
1. LinkedHashSet(): This constructor is used to create a default HashSet
LinkedHashSet<E> hs = new LinkedHashSet<E>();
2. LinkedHashSet(Collection C): Used in initializing the HashSet with the elements of the collection C.
LinkedHashSet<E> hs = new LinkedHashSet<E>(Collection c);
3. LinkedHashSet(int size): Used to initialize the size of the LinkedHashSet with the integer mentioned in the
parameter.
LinkedHashSet<E> hs = new LinkedHashSet<E>(int size);
4. LinkedHashSet(int capacity, float fillRatio): Can be used to initialize both the capacity and the fill ratio, also
called the load capacity of the LinkedHashSet with the arguments mentioned in the parameter.
LinkedHashSet<E> hs = new LinkedHashSet<E>(int capacity, int fillRatio);
Method
spliterator() Creates a late-binding and fail-fast Spliterator over the elements in this set
Example:
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class LinkedHashSetExample {
public static void main(String[] args) {
LinkedHashSet<Book> hs=new LinkedHashSet<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to hash table
hs.add(b1);
hs.add(b2);
hs.add(b3);
//Traversing hash table
for(Book b:hs){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}