Java TreeSet.headSet(E toElement)

Syntax

TreeSet.headSet(E toElement) has the following syntax.

public SortedSet <E> headSet(E toElement)

Example

In the following code shows how to use TreeSet.headSet(E toElement) method.


/*  w w  w.  ja v  a  2s  . com*/

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

public class Main {
   public static void main(String[] args) {
     TreeSet <Integer> tree = new TreeSet<Integer> ();
     
     tree.add(12);
     tree.add(13);
     tree.add(14);
     tree.add(15);
     tree.add(16);
     tree.add(17);
     
     // getting values less than 15
     TreeSet<Integer> treeheadset = (TreeSet)tree.headSet(15);  
 
     Iterator<Integer> iterator = treeheadset.iterator();
     
     while (iterator.hasNext()){
        System.out.println(iterator.next());
     }
   }    
}

The code above generates the following result.