TreeSet

Obtain head Set from TreeSet example

This is an example of how to obtain a head Set from a TreeSet in Java, using the headSet(E toElement) method of TreeSet. Getting a head Set from a TreeSet implies that you should:

  • Create a new TreeSet.
  • Populate the set with elements, with add(E e) API method of TreeSet.
  • Invoke the headSet(E toElement) API method of TreeSet. It will return a SortedSet, that is a portion of the TreeSet, whose keys are less than toElement. The returned set is backed by the original TreeSet. So any changes made to SortedSet will be reflected back to original TreeSet.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.util.SortedSet;
import java.util.TreeSet;
 
public class HeadsetTreeSet {
 
  public static void main(String[] args) {
 
    // Create a TreeSet and populate it with elements
    TreeSet treeSet = new TreeSet();
    treeSet.add("element_1");
    treeSet.add("element_3");
    treeSet.add("element_2");
    treeSet.add("element_4");
    treeSet.add("element_5");
 
    /*

SortedSet headSet(Object toElement) returns the portion of TreeSet whose keys are less than toElement.

The SortedSet returned is backed by the original TreeSet. So any changes made to SortedSet will 

be reflected back to original TreeSet.
    */
    SortedSet headSet = treeSet.headSet("element_3");
    System.out.println("headSet contains : " + headSet);
  }
}

Output:

headSet contains : [element_1, element_2]

 
This was an example of how to obtain a head Set from a TreeSet in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button