Java 6 - NavigableSet -headSet and tailSet Example Java Collections Framework

The below example explains the headSet and tailSet methods of the NavigableSet.

package examples;

import java.util.NavigableSet;
import java.util.TreeSet;
public class NavigableSetExample {

public static void main(String[] args) {
NavigableSet set = new TreeSet();
// Add elements in to the Navigable Set
set.add(1);
set.add(2);
set.add(3);
System.out.println(set);

// Head Set
System.out.println("Head Set :" + set.headSet(2));
System.out.println("Head Set including given integer: "+ set.headSet(2, true));

// Tail Set
System.out.println("Tail Set" + set.tailSet(2));
System.out.println("Tail Set including given integer: " + set.tailSet(2, false));
}

}

[1, 2, 3]
Head Set :[1]
Head Set including given integer: [1, 2]
Tail Set[2, 3]
Tail Set including given integer: [3]

No comments:

Post a Comment

Please Provide your feedback here