Showing posts with label Java-Collections. Show all posts
Showing posts with label Java-Collections. Show all posts

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.
 */

Friday, 19 October 2012

Comparable and Comparator example


 Difference between Comparable and Comparator


[1]. java.lang.Comparable

  
  To implements comparable interface, A class must implement a single method compareTo().

    int obj1.compareTo(obj2)

 
java.util.Comparator

    To implements comparator interface, A class must implement a single method compare().

    int compare (obj1,obj2)

[2] Comparable

If a class implements the java.lang.Comparable interface then it will be able to compare its instances
itself with its another object

Comparator

This class will not compare its instances but it will be able to compare some other class’s instances.
A comparator object is capable of comparing two different objects.

[3]  Comparable interface having public int compareTo(Object o) method  returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

Comparator interface having public int compare (Object o1, Object o2) method  returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

// This is the sample program for Comparable interface.

package com.corejava.gaurav.examples;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Collections;


@SuppressWarnings("rawtypes")
public class EmployeeComparableTestExample implements Comparable{
    private int empAge;
    private String empName;
   
    public EmployeeComparableTestExample(int age,String name){
        this.empAge = age;
        this.empName = name;
       
    }

    public int compareTo(Object obj){
        EmployeeComparableTestExample empTest = (EmployeeComparableTestExample)obj;
        int result = 0;
        Integer in1 = new Integer(this.empAge);
        Integer in2 = new Integer(empTest.empAge);
        result = in1.compareTo(in2);
        if(result==0){
            result = this.empName.compareTo(empTest.empName);
        }
        return result;
    }
   
    @SuppressWarnings({"unchecked" })
    public static void main(String args[]){

        List arrayLst = new ArrayList(0);
        arrayLst.add(new EmployeeComparableTestExample(55,"Nayan"));
        arrayLst.add(new EmployeeComparableTestExample(15,"Mihika"));
        arrayLst.add(new EmployeeComparableTestExample(34,"Dhiraj"));
        arrayLst.add(new EmployeeComparableTestExample(55,"Avantika"));
        Collections.sort(arrayLst);
        Iterator itr = arrayLst.iterator();
        while(itr.hasNext()){
            System.out.println(itr.next());
        }
    }
    @Override
    public String toString(){
        return "Employee Age - "+empAge +" And His Name is - "+empName;
    }
   
}


// This is the sample program for Comparator interface.

package com.corejava.gaurav.examples;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Employee2{
    int empId;
    String empName;
    public Employee2(int id,String name){
        this.empId = id;
        this.empName = name;
    }
   
    public int getEmpId() {
        return empId;
    }
    public void setEmpId(int empId) {
        this.empId = empId;
    }
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
    @Override
    public String toString(){
        return "Employee Id is "+ empId +" And Employee Name is "+empName;
    }
}


@SuppressWarnings("rawtypes")
public class EmployeeComparator implements Comparator{
   
    public int compare(Object obj1,Object obj2){
        int result = 0;
        Employee2 emp = (Employee2)obj1;
        Employee2 emp1 = (Employee2)obj2;
       
        Integer int1 = new Integer(emp.getEmpId());
        Integer int2 = new Integer(emp1.getEmpId());
       
        result = int1.compareTo(int2);
       
        if(result == 0){
            result = emp.getEmpName().compareTo(emp1.getEmpName());
       
        }
       
        return result;
    }

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

        List arLst = new ArrayList(0);
        arLst.add(new Employee2(32785,"Gaurav"));
        arLst.add(new Employee2(62653,"Pritish"));
        arLst.add(new Employee2(12345,"Anita"));
        arLst.add(new Employee2(32885,"Bhupesh"));
        Collections.sort(arLst, new EmployeeComparator());
        for(Object obj:arLst){
            System.out.println(obj);
                 }
        }
}

Note:-  In Java Comparable interface is used to implement natural ordering of object. String, Date and wrapper classes implements Comparable interface. Comparator is used for sorting customization.

With the help of comparator we can provide more then one order behavior while this is not true with comparable.

Use of StreamTokenizer


StreamTokenizer significance

The StreamTokenizer class is used to break any InputStream into a sequence of “tokens,” which are bits of text delimited by whatever we will choose. A stream tokenizer takes an input stream and parses it into tokens and it is allowing the tokens to be read one at a time.


//This is the sample program for counting words and numbers in a file available in file system.

package com.corejava.gaurav.examples;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamTokenizer;


public class countWordsAndNumbersUsingStreamToenizer {
   
    /**
     * Example method for using the StreamTokenizer class
     */
    public void countWordsAndNumbers(String filename) {
       
        StreamTokenizer sTokenizer = null;
        int wordCount = 0, numberCount = 0;
       
        try {
           
            sTokenizer = new StreamTokenizer(new FileReader(filename));
           
            while (sTokenizer.nextToken() != StreamTokenizer.TT_EOF) {
               
                if (sTokenizer.ttype == StreamTokenizer.TT_WORD)
                    wordCount++;
                else if (sTokenizer.ttype == StreamTokenizer.TT_NUMBER)
                    numberCount++;
            }
           
            System.out.println("Number of words in file: " + wordCount);
            System.out.println("Number of numbers in file: " + numberCount);
           
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
   
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new countWordsAndNumbersUsingStreamToenizer().countWordsAndNumbers("D://welcome.txt");
    }
}

Note: - Below is the contents of welcome.txt file

India is second biggest Country in Asia
234 hello 123 Welcome
7612 242542 4525 india
is great 145.( Sample text).

Collection Class methods example(binarySearch, sort, reverseOrder etc.)



//Sample Example for available methods of Collection class

package com.corejava.gaurav.examples;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;

public class CollectionsClassMethodTestExample {

    public static void main(String args[]){
        ArrayList<Integer> lst = new ArrayList<Integer>(0);
        lst.add(9);
        lst.add(7);
        lst.add(3);
        lst.add(10);
        Object obj = Collections.min(lst);
        System.out.println("miminum obj is-"+obj);
       
        Object obj1 = Collections.max(lst);
        System.out.println("maximum object is-"+obj1);
       
               
        ArrayList<Integer> numLst = new ArrayList<Integer>(0);
        numLst.add(15);
        numLst.add(21);
        numLst.add(33);
        numLst.add(44);
       
        Collections.copy(numLst, lst);
       
        System.out.println("numlist is-"+numLst);
       
        ArrayList<String> slst = new ArrayList<String>(0);
        slst.add("A");
        slst.add("B");
        slst.add("C");
        slst.add("D");
       
        Enumeration e = Collections.enumeration(slst);
        while(e.hasMoreElements()){
            System.out.println("elements are-"+e.nextElement());
        }
       
        Collections.sort(lst);
        System.out.println("Elements after sorting-"+lst);
        int index = Collections.binarySearch(lst, 9);
        System.out.println("element available at index-> "+index);
       
        Collections.swap(lst,0,3);
        System.out.println("Lst is after swap="+lst);
       
       
        Comparator comparater = Collections.reverseOrder();
        Collections.sort(slst,comparater);
        System.out.println("slst elements are after sort in desc order-"+slst);
    }
}

CopyOnWriteArrayList and CopyOnWriteArraySet


 Fundamentals of CopyOnWriteArrayList and CopyOnWriteArraySet

[1.] The basic thing behind the CopyOnWriteArrayList and CopyOnWriteArraySet is all mutable operations make a copy of the backing array first, make the change to the copy, and then replace the copy.

[2]. If we want to share the data structure among several threads where we have few writes and many reads then we can use CopyOnWriteArrayList and CopyOnWriteArraySet.

[3]. The CopyOnWrite... collections avoid ConcurrentModificationException issues during traversal by traversing through the original collection and the modifications happening in a copy of the original store.

[4]. CopyOnWriteArrayList is a thread-safe version of ArrayList without the syncrhonized access limitations. Both are available in java.util.concurrent package.
 


//Sample example of CopyOnWriteArrayList  which is used to avoid ConcurrentModificationException and  UnsupportedOperationException
package com.corejava.gaurav.examples;

import java.util.Iterator;
import java.util.ListIterator;
import java.util.concurrent.CopyOnWriteArrayList;


public class CopyOnWriteArrayListTestExample {

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String args[]){
        CopyOnWriteArrayList clst = new CopyOnWriteArrayList();
        clst.add("Shivam");
        clst.add("Priyanka");
        ListIterator itr = clst.listIterator();
        while(itr.hasNext()){
            System.out.println("Elements are->"+itr.next());
            clst.add("Dhanush");
       
        }
        Iterator itr1 = clst.iterator();
        while(itr1.hasNext()){
            System.out.println("after Modification Elements are->"+itr1.next());
        }
    }
}


//Sample example of CopyOnWriteArraySet  which is used to avoid ConcurrentModificationException and  UnsupportedOperationException

package com.corejava.gaurav.examples;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;


public class CopyOnWriteArraySetTestExample {
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String args[]){
        CopyOnWriteArraySet cset = new CopyOnWriteArraySet();
        cset.add("Mitali");
        cset.add("Nikhil");
       
        Iterator itr = cset.iterator();
       
        while(itr.hasNext()){
            System.out.println("Set Elements are-"+itr.next());
            cset.add("Vishal");
        }
       
        Iterator itr1 = cset.iterator();
       
        while(itr1.hasNext()){
            System.out.println("After Modification Set Elements are-"+itr1.next());
           
        }
    }
}

Thursday, 18 October 2012

How to create a zip file by converting jar file using Java API




//Sample example to create a zip file from a jar file using java api.


package com.gaurav.java.others;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class GZipFile {

 private static final String OUTPUT_GZIP_FILE = "C:/zipFolder/javaee.zip";
 private static final String SOURCE_FILE = "C:/zipFolder/javaee.jar";
public static void main(String[] args) {

                 GZipFile gZip = new GZipFile();
                 gZip.gzipIt();
              }
 /**
  * GZip it
  *
  * @param zipFile
  *            output GZip file location
  */
 public void gzipIt() {
          byte[] buffer = new byte[1024];
             try {
                   GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(
                   OUTPUT_GZIP_FILE));
                   FileInputStream in = new FileInputStream(SOURCE_FILE);
                   int len;
                     while ((len = in.read(buffer)) > 0) {
                     gzos.write(buffer, 0, len);
                    }
                  in.close();
                  gzos.finish();
                  gzos.close();
                  System.out.println(" File Convertion Completed");
            } catch (IOException ex) {
          ex.printStackTrace();
         }
     }
}