How to work with java6’s Navigable Set and Navigable Map

NavigableSet and NavigableMap Interfaces were included in Java6’s Collection API. TreeSet and TreeMap are the Classes that implement these Interfaces.

package com.bharat.collection;

import java.util.Arrays;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.TreeSet;

public class NavigableSetExample {

    public static void main(String[] args) {

        NavigableSet<String> navigableSet = new TreeSet<String>(Arrays.asList(
                "BBB", "ZZZ", "AAA", "PPP", "NNN"));

        Iterator<String> iterator = navigableSet.descendingIterator();
        // Showing original Set
        System.out.println("Original Set :");
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        iterator = navigableSet.iterator();

        System.out.println("Sorted Navigable Set :");

        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        System.out.println("Head Set : " + navigableSet.headSet("XXX"));

        System.out.println("Tail Set : " + navigableSet.tailSet("PPP", false));

        System.out.println("Sub Set : "
                + navigableSet.subSet("BBB", true, "ZZZ", true));

        System.out.println("Lowest Element : " + navigableSet.first());
        System.out.println("Highest Element : " + navigableSet.last());

        System.out.println("Original Set : " + navigableSet);
        System.out.println("Reverse Set : " + navigableSet.descendingSet());
    }
}

Output is :

Original Set :
ZZZ
PPP
NNN
BBB
AAA
Sorted Navigable Set :
AAA
BBB
NNN
PPP
ZZZ
Head Set : [AAA, BBB, NNN, PPP]
Tail Set : [ZZZ]
Sub Set : [BBB, NNN, PPP, ZZZ]
Lowest Element : AAA
Highest Element : ZZZ
Original Set : [AAA, BBB, NNN, PPP, ZZZ]
Reverse Set : [ZZZ, PPP, NNN, BBB, AAA]
Advertisements

, , , , , , ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: