Java TreeSet.headSet(E toElement, boolean inclusive)

Syntax

TreeSet.headSet(E toElement, boolean inclusive) has the following syntax.

public NavigableSet <E> headSet(E toElement,   boolean inclusive)

Example

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


import java.util.Iterator;
import java.util.TreeSet;
//  w ww.j av  a 2 s .c  om
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 for 15 inclusive true
     TreeSet<Integer> treeheadsetincl = (TreeSet)tree.headSet(15, true);  
 
     Iterator<Integer> iterator = treeheadsetincl.iterator();
     
     System.out.println("Tree set data for '15' inclusive TRUE: ");     
     while (iterator.hasNext()){
        System.out.println(iterator.next());
     }
     
     // getting values for 15 inclusive false
     treeheadsetincl = (TreeSet)tree.headSet(15, false);  
 
     iterator = treeheadsetincl.iterator();
     
     while (iterator.hasNext()){
        System.out.println(iterator.next());
     }
   }    
}

The code above generates the following result.