Wednesday, 27 March 2013

JDK6 Collection New Features ArrayDeque, LinkedBlockingDeque, ConcurrentSkipListSet and ConcurrentSkipListMap Example

Deque and ArrayDeque

/*Deque interface defines some methods that access the element at both ends. Which means that

  by the methods of this interface we can add and remove the elements at both ends.
 
  ArrayDeque is a class that implements Deque.It can perform faster than Stack when used as a stack and 
 
  faster than LinkedList when used as a queue.

 */

package com.gaurav.jdk6newfeatures;


import java.util.ArrayDeque;

import java.util.Iterator;


public class ArrayDequeExample

{

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String arg[])

            {

                           ArrayDeque arrayDeque = new ArrayDeque();

                        //Inserting elements using various methods of ArrayDeque

                           arrayDeque.add("Samsung");

                           arrayDeque.addFirst("Sony");

                           arrayDeque.offerFirst("Micromax"); 

                           arrayDeque.offerLast("LG");

                        Iterator it = arrayDeque.iterator();

                        while(it.hasNext())

                        {

                                    System.out.println(it.next());

                        } 
                       

                        System.out.println("Retrieving First Element :" + arrayDeque.peekFirst());

                        System.out.println("Retrieving Last Element :" + arrayDeque.peekLast());

                        System.out.println("Removing First  Element :" + arrayDeque.pollFirst());

                        System.out.println("Removing Last  Element :" + arrayDeque.pollLast());

                        //Traversal in Reverse order

                        System.out.println("Remaining Elements :");

                        Iterator it1 = arrayDeque.descendingIterator();

                        while(it1.hasNext())

                        {

                                    System.out.println(it1.next());

                        }                    

            }

}


/*
Remember : 

 1. peekFirst() method retrieves first element from the ArrayDeque.

 2. peekLast() method retrieves last element from the ArrayDeque.

 3. pollFirst() method removes first element from the ArrayDeque. 

 4. pollLast() method removes last element from the ArrayDeque.
*/


BlockingDeque and LinkedBlockingDeque

/*
A BlockingDeque is similar to Deque and provides additional functionality.

When we tries to insert an element in a BlockingDeque, which is already full,

it can wait till the space become available for inserting an element. We can also

specify the wait time period limit.

BlockingDeque methods are available in four flavor:-

    Method throws exception
    Method returns special value
    Method that blocks(Waits indefinitely for space to be available)
    Method that times out(Waits for a given time period for space to be available)
*/

package com.gaurav.jdk6newfeatures;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

public class LinkedBlockingDequeExample implements Runnable{
   
    @SuppressWarnings("rawtypes")
   
    BlockingDeque blockingDeque = new LinkedBlockingDeque(1);
    volatile boolean flag = true;
   
    @SuppressWarnings("unchecked")
    public void run()
    {
        try
        {
            /*First thread once enters into the block it modifies
              instance variable flag to false and prevents second
              thread to enter into the block */
             if(flag)
            {
                flag = false;
                Thread.sleep(3000);//Makes the Thread to sleep for 3 seconds
                System.out.println("Removing the element - "+blockingDeque.peek());
                blockingDeque.poll();//Removing an element from collection
            }
            else
            {
                System.out.println("Waiting ");   
                /*This method makes to wait till the first thread removes an elements*/
                blockingDeque.put("Kumar");
                System.out.println("Inserted element - "+blockingDeque.peek());   
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
   
    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws Exception
    {
        LinkedBlockingDequeExample linkedBlockingDequeExample = new LinkedBlockingDequeExample();
        linkedBlockingDequeExample.blockingDeque.offer("Gaurav");
        System.out.println("Inserted the element - "+linkedBlockingDequeExample.blockingDeque.peek());   
        Thread threadObj1 = new Thread(linkedBlockingDequeExample);
        threadObj1.start();
        Thread threadObj2 = new Thread(linkedBlockingDequeExample);
        threadObj2.start();       
    }
}

NavigableSet and ConcurrentSkipListSet


/* NavigableSet extends SortedSet and is implemented by TreeSet and concurrentSkipListSet (a new class in Java collection).

   ConcurrentSkipListSet is one of the class that implements NavigableSet and it is used to return the closest matches of elements.
  
   It includes methods to return iterators in ascending and descending orders, as well as methods that return a sorted or navigable set
  
   for a special portion of data.

 */

package com.gaurav.jdk6newfeatures;

import java.util.Iterator;
import java.util.NavigableSet;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

public class ConcurrentSkipListSetExample

{

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String[] args)

    {

        System.out.println("Example of Navigable Set");

        NavigableSet navigableSet = new ConcurrentSkipListSet();

        navigableSet.add("30");

        navigableSet.add("90");

        navigableSet.add("20");

        navigableSet.add("10");

        navigableSet.add("80");

        navigableSet.add("70");

        Iterator iterator = navigableSet.iterator(); // Returns an iterator over the
                                                // elements in navigable set, in
                                                // ascending order.

        System.out.print("In ascending order :");

        while (iterator.hasNext())

        { // Ascending order list

            System.out.print(iterator.next() + " ");

        }

        System.out.println(); // Descending order list

        System.out.println("In descending order : " + navigableSet.descendingSet()
                + "\n");

        System.out.println("Remove element: " + navigableSet.pollLast());

        // After removing the last element, now get navigable set

        System.out.println("Now navigable set: " + navigableSet.descendingSet());

        ConcurrentSkipListSet<Integer> conSkipListSet = new ConcurrentSkipListSet<Integer>();

        conSkipListSet.add(40);
        conSkipListSet.add(35);
        conSkipListSet.add(25);
        conSkipListSet.add(55);
        System.out.println("Elements in the collections are");

        for (Integer i : conSkipListSet) {
            System.out.println(i);
        }

        /* Retrieve immediate element less than or equal to the given element */
        System.out.println("Floor    " + conSkipListSet.floor(28));

        /* Retrieve immediate element greater than or equal to the given element */
        System.out.println("Ceiling  " + conSkipListSet.ceiling(20));

        /* Retrieve immediate element less than the given element */
        System.out.println("Lower    " + conSkipListSet.lower(30));

        /* Retrieve immediate element greater than the given element */

        System.out.println("heigher  " + conSkipListSet.higher(40));
        System.out.println("Head Elements ");
        Set<Integer> cslsHeadView = conSkipListSet.headSet(35);

        // HeadSet will exclude the given element

        for (Integer i : cslsHeadView) {
            System.out.println(i);
        }
        Set<Integer> cslsTailView = conSkipListSet.tailSet(35);

        // TailSet will include the given element

        System.out.println("Tail Elements");
        for (Integer i : cslsTailView) {
            System.out.println(i);
        }

    }

}


/*
  Remember :
  
  Data insertion is possible in NavigableSet using the "add()" method.
 
  NavigableSet provides the facility for retrieving the data in ascending and descending order.
 
  The "descendingSet()" method returns the data from the NavigableSet in descending order.
 
  We can use "pollFirst()" method to remove the element from the set at first position and " pollLast()" method to remove
 
  element from NavigableSet at last position.
 */


NaviagableMap and ConcurrentSkipListMap


/* NaviagableMap is similar to NaviagableSet. In NavigableSet, methods use to return values, but in NaviagableMap methods
  
   used to return the key,value pair.ConcurrentSkipListMap is the one of the class which implements NaviagableMap.
*/
package com.gaurav.jdk6newfeatures;

import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;
import java.util.SortedMap;
import java.util.concurrent.ConcurrentSkipListMap;

public class ConcurrentSkipListMapExample {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String[] arg)

    {

        System.out.println("Example of Navigable Map ");

        NavigableMap navmap = new ConcurrentSkipListMap();

        navmap.put(1, "January");

        navmap.put(2, "February");

        navmap.put(3, "March");

        navmap.put(4, "April");

        navmap.put(5, "May");

        navmap.put(6, "June");

       
        System.out.println("Data in the navigable map: "
                + navmap.descendingMap() + "\n");

        // Retrieving first data

        System.out.println("First data: " + navmap.firstEntry() + "\n");

        // Retrieving last data

        System.out.print("Last data: " + navmap.lastEntry() + "\n");

        // Retrieving the nearest less than or equal to the given key

        System.out.println("Nearest less than or equal to the given key: "
                + navmap.floorEntry(5) + "\n");

        // Retrieving the greatest key strictly less than the given key

        System.out
                .println("Retrieving the greatest key strictly less than the given key: "
                        + navmap.lowerEntry(3));

        // Retrieving a key - value associated with the least key strictly greater than the given key
       
        System.out
                .println("Retriving data from navigable map greater than the given key:    "
                        + navmap.higherEntry(5) + "\n");

        // Removing first entry

        System.out.println("Removing First: " + navmap.pollFirstEntry());

        // Removing last entry

        System.out.println("Removing Last: " + navmap.pollLastEntry() + "\n");

        // Displaying all data

        System.out.println("Now data: " + navmap.descendingMap());

       
        NavigableMap navigableMap = new ConcurrentSkipListMap();
       
        navigableMap.put(1,"First");
        navigableMap.put(2,"Second");
        navigableMap.put(3,"Third");
        navigableMap.put(4,"Fourth");
        navigableMap.put(5,"Fifth");
        navigableMap.put(6,"Sixth");
       
        /* It Retrieves the key - value pair immediately lesser than the given key */
        Map.Entry ae = navigableMap.lowerEntry(5);
       
        /* Map.Entry is a Static interface nested inside Map
           interface,It is used to hold key and value */
       
        System.out.println("Key - " + ae.getKey());
        System.out.println("Value - "+    ae.getValue());
       
        /* Retrieves key - value pairs equal to and greater then the given key */
       
        SortedMap sortedMap = navigableMap.tailMap(3);
       
        Set<Integer> s = sortedMap.keySet();
       
        System.out.println("Tail elements are:-");
        for(Integer i:s)
        {
            System.out.println("Key - "+ i + "Value - "+ sortedMap.get(i));
            }
        }
    }


/*
 Remember : 

  1. lowerEntry() method retrieves less than the givenkey (or) null.
 
  2. floorEntry() method retrieves less than or equal to the givenkey (or) null.

  3. headMap() method retrieves all elements less than the givenkey. 

  4. tailMap() method retrieves all elements greater than or equal to the givenkey.
 */

1 comment: