Home » Core Java » util » TreeSet » Obtain head Set from TreeSet example

About Ilias Tsagklis

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

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.

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 our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments