21 Sept 2012

HashSet in java

/* hashset in java example, hashset in java example program */

HashSet is a collection. You can not store duplicate value in HashSet.
 
import java.util.HashSet; 
public class HashSetDemo
{
public static void main(String[] arg)
{
j
ava.util.HashSet hs = new java.util.HashSet(); 

hs.add("Bharat");
hs.add("Gyan"); 
hs.add("Ankita");
hs.add("Sathya");
System.out.println("All data of HashSet : "+
hs); 

}

Output :
All data of HashSet : [Gyan,Ankita,Sathya,Bharat]

Append all elements of other Collection to Java ArrayList

/* append all elements of other collection to java arraylist example */

import java.util.ArrayList;
import java.util.Vector;

public class AppendCollectionToArrayListExample 
{
  public static void main(String[] args) 
  {
    //create an ArrayList object
    
java.util.ArrayList arrayList = new java.util.ArrayList();
  
    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
  
    //create a new Vector object
    
java.util.Vector v = new java.util.Vector();
    v.add("4");
    v.add("5");
  
    /*
      boolean addAll(
java.util.Collection c) method.
    */
  
    //append all elements of Vector to ArrayList
    arrayList.addAll(v);
  
 System.out.println("After appending all elements of Vector,ArrayList contains..");
    for(int i=0; i<arrayList.size(); i++)
      System.out.println(arrayList.get(i));

  }
}

Output:
After appending all elements of Vector, ArrayList contains..
1
2
3
4
5

Copy Elements of ArrayList to Java Vector Example

/* Copy Elements of ArrayList to Java Vector Example, copy elements of arraylist to vector */

import java.util.ArrayList;
import java.util.Collections;
import java.util.Vector;

public class CopyArrayListToVectorExample 
{
  public static void main(String[] args) 
   {
    //create an ArrayList object
    
java.util.ArrayList arrayList = new java.util.ArrayList();
  
    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("4");
    arrayList.add("2");
    arrayList.add("5");
    arrayList.add("3");
  
    //create a Vector object
    
java.util.Vector v = new java.util.Vector();
  
    //Add elements to Vector
    v.add("A");
    v.add("B");
    v.add("D");
    v.add("E");
    v.add("F");
    v.add("G");
    v.add("H");
  
    /*
      To copy elements of Java ArrayList to Java Vector use,
      static void copy(
java.util.List dstList, java.util.List sourceList) method of Collections class.
    
      This method copies all elements of source list to destination list. After copy index of the elements in both source and destination lists would be identical.
    
      The destination list must be long enough to hold all copied elements. If it is longer than that, the rest of the destination list's elments would remains unaffected.   
    */
  
    System.out.println("Before copy, Vector Contains : " + v);
  
    //copy all elements of ArrayList to Vector
    
java.util.Collections.copy(v,arrayList);
  
    System.out.println("After Copy, Vector Contains : " + v); 
  }
}


Output:
Before copy Vector Contains : [A, B, D, E, F, G, H]
After Copy Vector Contains : [1, 4, 2, 5, 3, G, H]

Copy Elements of Vector to Java ArrayList Example

import java.util.ArrayList;
import java.util.Collections;
import java.util.Vector;

public class CopyVectorToArrayListExample 
{
  public static void main(String[] args) 
   {    
    //create a Vector object
    Vector v = new Vector();
  
    //Add elements to Vector
    v.add("1");
    v.add("2");
    v.add("3");
  
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
  
    //Add elements to Arraylist
    arrayList.add("One");
    arrayList.add("Two");
    arrayList.add("Three");
    arrayList.add("Four");
    arrayList.add("Five");
  
    /*
      To copy elements of Java Vector to Java ArrayList use,
      static void copy(List dstList, List sourceList) method of Collections class.
    
      This method copies all elements of source list to destination list. After copy index of the elements in both source and destination lists would be identical.
    
      The destination list must be long enough to hold all copied elements. If it  is longer than that, the rest of the destination list's elments would remain
      unaffected.     
    */
  
    System.out.println("Before copy ArrayList Contains : " + arrayList);
  
    //copy all elements of Vector to ArrayList using copy method of      Collections  class
    Collections.copy(arrayList,v);
  
    /*
      Please note that, If ArrayList is not long enough to hold all elements of
      Vector, it throws IndexOutOfBoundsException.
    */

    System.out.println("After Copy ArrayList Contains : " + arrayList); 
  }
}

Output:
Before copy ArrayList Contains : [One, Two, Three, Four, Five]
After Copy ArrayList Contains : [1, 2, 3, Four, Five]

Sorting ArrayList in descending order

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

public class SortArrayListExample 
{
  public static void main(String[] args) 
  {  
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
  
    //Add elements to Arraylist
    arrayList.add("A");
    arrayList.add("B");
    arrayList.add("C");
    arrayList.add("D");
    arrayList.add("E");
  
    /*
      To get comparator that imposes reverse order on a Collection use
      static Comparator reverseOrder() method of Collections class
    */
  
    Comparator comparator = Collections.reverseOrder();
  
    System.out.println("Before sorting ArrayList in descending order : "+arrayList);
  
    /*
      To sort an ArrayList using comparator use,
      static void sort(List list, Comparator c) method of Collections class.
    */
  
    Collections.sort(arrayList,comparator);
    System.out.println("After sorting ArrayList in descending order : "+arrayList);
  
  }
}

Output:
Before sorting ArrayList in descending order : [A, B, C, D, E]
After sorting ArrayList in descending order : [E, D, C, B, A]

Sort elements of Java ArrayList Example

import java.util.ArrayList;
import java.util.Collections;

public class SortArrayListExample 
{
  public static void main(String[] args) 
   {  
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
  
    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("3");
    arrayList.add("5");
    arrayList.add("2");
    arrayList.add("4");

    /*
    To sort an ArrayList object, use Collection.sort method. This is a
    static method. It sorts an ArrayList object's elements into ascending order.
    */
    Collections.sort(arrayList);
  
    //display elements of ArrayList
    System.out.println("ArrayList elements after sorting in ascending order : ");
    for(int i=0; i<arrayList.size(); i++)
      System.out.println(arrayList.get(i));

  }
}

Output:
ArrayList elements after sorting in ascending order :
1
2
3
4
5

Sorting String Array Example in java

import java.util.Arrays;

public class SortStringArrayExample 
  {      
        public static void main(String args[])
          {              
                //String array

              String[] strNames = new String[]{"John", "alex", "Chris", "williams",  "Mark", "Bob"};
              
                /*
                 * To sort String array in java, use Arrays.sort method.
                 * Sort method is a static method.               *
                 */
              
                //sort String array using sort method
                Arrays.sort(strNames);
              
                System.out.println("String array sorted (case sensitive)");
              
                //print sorted elements
                for(int i=0; i < strNames.length; i++){
                        System.out.println(strNames[i]);
                }
              
                /*
                 * Please note that, by default Arrays.sort method sorts the        Strings
                 * in case sensitive manner.
                 *
                 * To sort an array of Strings irrespective of case, use
                 * Arrays.sort(String[] strArray,                                              String.CASE_INSENSITIVE_ORDER) method instead.
                 */
              
                //case insensitive sort
                Arrays.sort(strNames);
              
                System.out.println("String array sorted (case insensitive)");
                //print sorted elements again
                for(int i=0; i < strNames.length; i++){
                        System.out.println(strNames[i]);
                }

        }
}

Output::
String array sorted (case sensitive)
Bob
Chris
John
Mark
alex
williams
String array sorted (case insensitive)
Bob
Chris
John
Mark
alex
williams

Search an element of Java ArrayList

import java.util.ArrayList;
public class SearchExample 
{
  public static void main(String[] args) 
  {  
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
  
    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    arrayList.add("4");
    arrayList.add("5");
    arrayList.add("1");
    arrayList.add("2");

    /*
      To check whether the specified element exists in Java ArrayList use
      boolean contains(Object element) method.
      It returns true if the ArrayList contains the specified objct, false
      otherwise.
    */
  
    boolean blnFound = arrayList.contains("2");
    System.out.println("Does arrayList contain 2 ? " + blnFound);

    /*
      To get an index of specified element in ArrayList use
      int indexOf(Object element) method.
      This method returns the index of the specified element in ArrayList.
      It returns -1 if not found.
    */

    int index = arrayList.indexOf("4");
    if(index == -1)
      System.out.println("ArrayList does not contain 4");
    else
      System.out.println("ArrayList contains 4 at index :" + index);
    
    /*
      To get last index of specified element in ArrayList use
      int lastIndexOf(Object element) method.
      This method returns index of the last occurrence of the
      specified element in ArrayList. It returns -1 if not found.
    */

    int lastIndex = arrayList.lastIndexOf("1");
    if(lastIndex == -1)
      System.out.println("ArrayList does not contain 1");
    else
      System.out.println("Last occurrence of 1 in ArrayList is at index :"+ lastIndex);
    
  } 
}
 
Output would be
Does arrayList contain 2 ? true
ArrayList contains 4 at index :3
Last occurrence of 1 in ArrayList is at index :5

Replace an element at specified index of Java ArrayList

import java.util.ArrayList;
public class ArrayListExample 
{
  public static void main(String[] args) 
   {
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
  
    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
  
    /*
      To replace an element at the specified index of ArrayList use
      Object set(int index, Object obj) method.
      This method replaces the specified element at the specified index in the
      ArrayList and returns the element previously at the specified position.
    */
    arrayList.set(1,"REPLACED ELEMENT");

    System.out.println("ArrayList contains...");
    //display elements of ArrayList
    for(int index=0; index < arrayList.size(); index++)
      System.out.println(arrayList.get(index));
  
  }
}


Output would be
ArrayList contains...
1
REPLACED ELEMENT
3

Converting Object into integer in java


// get array
Object ia[] = al.toArray();
int sum = 0;
// sum the array
for(int i=0; i<ia.length; i++)
sum += ((Integer) ia[i]).intValue();
System.out.println("Sum is: " + sum);
}
}

The output from the program is shown here:

Contents of al: [1, 2, 3, 4]
Sum is: 10

Converting ArrayList into array in java

When working with ArrayList, you will sometimes want to obtain an actual array that contains the contents of the list. As explained earlier, you can do this by calling toArray( ).

// get array
Object ia[] = al.toArray();
int sum = 0;
// sum the array
for(int i=0; i<ia.length; i++)
sum += ((Integer) ia[i]).intValue();
System.out.println("Sum is: " + sum);
}
}

The output from the program is shown here:

Contents of al: [1, 2, 3, 4]
Sum is: 10

ArrayList in java with example

ArrayList class provides methods for basic array operations:
add( Object o ) - puts reference to object into ArrayList
get( int index ) - retrieves object reference from ArrayList index position
size() - returns ArrayList size
remove( int index ) - removes the element at the specified position in this list. Shifts any subsequent elements to the left and returns the element that was removed from the list.
indexOf( Object o) - finds the index in this list of the first occurrence of the specified element
clear() - removes all of the elements

In this example we are going to show the use of java.util.ArrayList. We will be creatiing an object of ArrayList class and performs various operations like adding removing the objects.

import java.util.*;
public class ArrayListDemo
{
  public static void main(String[] args)
 {
  ArrayList<Object> arl=new ArrayList<Object>();
  Integer i1=new Integer(10);
  Integer i2=new Integer(20);
  Integer i3=new Integer(30);
  Integer i4=new Integer(40);
  String s1="Sathya";
  System.out.println("The content of arraylist is: " + arl);
  System.out.println("The size of an arraylist is: " + arl.size());
  arl.add(i1);
  arl.add(i2);
  arl.add(s1);
  System.out.println("The content of arraylist is: " + arl);
  System.out.println("The size of an arraylist is: " + arl.size());
  arl.add(i1);
  arl.add(i2);
  arl.add(i3);
  arl.add(i4);
  Integer i5=new Integer(50);
  arl.add(i5);
  System.out.println("The content of arraylist is: " + arl);
  System.out.println("The size of an arraylist is: " + arl.size());
  arl.remove(3);
  Object a=arl.clone();
  System.out.println("The clone is: " + a);
  System.out.println("The content of arraylist is: " + arl);
  System.out.println("The size of an arraylist is: " + arl.size());
  }
}
 
Output:
The content of arraylist is: []
The size of an arraylist is: 0
The content of arraylist is: [10, 20, Sathya]
The size of an arraylist is: 3
The content of arraylist is: [10, 20, Sathya, 10, 20, 30, 40, 50]
The size of an arraylist is: 8
The clone is: [10, 20, Sathya, 20, 30, 40, 50]
The content of arraylist is: [10, 20, Sathya, 20, 30, 40, 50]
The size of an arraylist is: 7

sorting vector in ascending order

import java.util.Vector;
import java.util.Collections;

public class SortJavaVectorExample {

  public static void main(String[] args) {
  
    //create Vector object
    Vector v = new Vector();
  
    //Add elements to Vector
    v.add("1");
    v.add("3");
    v.add("5");
    v.add("2");
    v.add("4");

    /*
      To sort a Vector object, use Collection.sort method. This is a
      static method. It sorts an Vector object's elements into ascending order.
    */
    Collections.sort(v);
  
    //display elements of Vector
    System.out.println("Vector elements after sorting in ascending order : ");
    for(int i=0; i<v.size(); i++)
      System.out.println(v.get(i));

  }
}


Output:
Vector elements after sorting in ascending order :
1
2
3
4
5

Sorting Vector in descending order

import java.util.Vector;
import java.util.Collections;
import java.util.Comparator;
 
public class SortVectorExample {
 
  public static void main(String[] args) {
  
    //create a Vector object
    Vector v = new Vector();
  
    //Add elements to Vector
    v.add("1");
    v.add("2");
    v.add("3");
    v.add("4");
    v.add("5");
  
    /*
      To get comparator that imposes reverse order on a Collection use
      static Comparator reverseOrder() method of Collections class
    */
  
    Comparator comparator = Collections.reverseOrder();
  
    System.out.println("Before sorting Vector in descending order : " + v);
  
    /*
      To sort an Vector using comparator use,
      static void sort(List list, Comparator c) method of Collections class.
    */
  
    Collections.sort(v,comparator);
    System.out.println("After sorting Vector in descending order : " + v);
  
  }
}
 
Output:
Before sorting Vector in descending order : [1, 2, 3, 4, 5]
After sorting Vector in descending order : [5, 4, 3, 2, 1]

Vector in java example

Vector class extends AbstractList and implements List, RandomAccess, Cloneable, Serializable. Vector is synchronized.

Here are the Vector constructors:
Vector( )
Vector(int size)
Vector(int size, int incr)
Vector(Collection c)
The first form creates a default vector, which has an initial size of 10.
The second form creates a vector whose initial capacity is specified by size.
The third form creates a vector whose initial capacity is specified by size and whose increment is specified by incr.
The increment specifies the number of elements to allocate each time that a vector is resized upward.
The fourth form creates a vector that contains the elements of collection c.

Methods of a Vector class.
add(Object o): It adds the element in the end of the Vector
ex: vector.add(str);

size(): It gives the number of element in the vector.
ex: int size=vector.size();

elementAt(int index): It returns the element at the specified index.
ex: Object o=vector.elementAt(2);

firstElement(): It returns the first element of the vector.
ex: Object o=vector.firstElement();

lastElement(): It returns  last element.
ex: Object o=vector.lastElement();

removeElementAt(int index): It deletes the element from the given index.
ex: vector.removeElementAt(2);

elements(): It returns an enumeration of the element
ex: Enumeration e=vector.elements();

import java.util.*;
public class VectorExample
{
 public static void main(String[] args)
 {
  Vector vector = new Vector();
  int primitiveType = 10;
  Integer wrapperType = new Integer(20);
  String str = "Sathya";
  vector.add(primitiveType);
  vector.add(wrapperType);
  vector.add(str);
  vector.add(2, new Integer(30));
  System.out.println("the elements of vector: " + vector);
  System.out.println("The size of vector are: " + vector.size());
  System.out.println("The elements at position 2 is: "+vector.elementAt(2));
  System.out.println("The first element of vector is: "+vector.firstElement());
  System.out.println("The last element of vector is: "+vector.lastElement());
  vector.removeElementAt(2);
  Enumeration e=vector.elements();
  System.out.println("The elements of vector: "+vector);
  while(e.hasMoreElements())
  {
  System.out.println("The elements are: "+e.nextElement());
  }
  Iterator vItr = vector.iterator();
  System.out.println("Elements in vector:");
  while(vItr.hasNext())
  System.out.print(vItr.next() + " "); 
 }
}

Output:
the elements of vector: [10, 20, 30, Sathya]
The size of vector are: 4
The elements at position 2 is: 30
The first element of vector is: 10
The last element of vector is: Sathya
The elements of vector: [10, 20, Sathya]
The elements are: 10
The elements are: 20
The elements are: Sathya
Elements in vector:
10 20 Sathya

Differences between Iterator and ListIterator in java

Iterator is an interface in the collection framework. Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time.
Iterator gives you the ability to access the collection in forward direction.

It has methods hasNext() and next().
hasNext( ) returns false when the end of the list has been reached. Otherwise it returns true.
obtain each element by calling next( ).

ListIterator is an interface in the collection framework. Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an listIterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time. Iterator gives you the ability to access the collection either in forward direction or backward direction.

It has methods hasNext(), hasPrevious(), next() and previous().
hasNext( ) returns false when the end of the list has been reached. Otherwise it returns true.
hasPrevious() returns true if this list iterator has more elements when traversing the list in the reverse direction. Otherwise it returns false.
obtain each element by calling next( ).
previous() returns the previous element in the list.

ListIterator in java example

ListIterator is an interface in the collection framework. Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an listIterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time. Iterator gives you the ability to access the collection either in forward direction or backward direction.

It has methods hasNext(), hasPrevious(), next() and previous().
hasNext( ) returns false when the end of the list has been reached. Otherwise it returns true.
hasPrevious() returns true if this list iterator has more elements when traversing the list in the reverse direction. Otherwise it returns false.
obtain each element by calling next( ).
previous() returns the previous element in the list.

public class sample {
 
  public static void main(String[] args) {
    //create an object of ArrayList
    ArrayList aList = new ArrayList();
 
    //Add elements to ArrayList object
    aList.add("1");
    aList.add("2");
    aList.add("3");
    aList.add("4");
    aList.add("5");
 
    //Get an object of ListIterator using listIterator() method
    ListIterator listIterator = aList.listIterator();
 
     
    System.out.println(" forward direction using ListIterator");
    while(listIterator.hasNext())
      System.out.println(listIterator.next());
 
  
    System.out.println("reverse direction using ListIterator");
    while(listIterator.hasPrevious())
      System.out.println(listIterator.previous());
   }
}

Output :
forward direction using ListIterator
1
2
3
4
5
reverse direction using ListIterator
5
4
3
2
1

Iterator in java example

Iterator is an interface in the collection framework. Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time.
Iterator gives you the ability to access the collection in forward direction.

It has methods hasNext() and next().
hasNext( ) returns false when the end of the list has been reached. Otherwise it returns true.
obtain each element by calling next( ).

import java.util.*;

public class iteratordemo
{
public static void main(String[] args)
{
List l = new ArrayList();
for (int i = 1; i < 6; i++)
{
l.add(i);
}
Iterator it = l.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}

Output :
1 2 3 4 5

descending a hashmap in java by key

//descending a hashmap in java by key
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class SortMapExample
{
   public static void main(String[] args)
   {
    Map<String,String> unsortMap=new HashMap<String,String>();
    unsortMap.put("2", "A");
    unsortMap.put("4", "B");
    unsortMap.put("1", "D");
    unsortMap.put("6", "c");
    unsortMap.put("3", "d");
    unsortMap.put("5", "C");
    unsortMap.put("7", "b");
    unsortMap.put("8", "a");
    System.out.println("Unsort Map......");
   
        for(Map.Entry entry : unsortMap.entrySet())
        {
     System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
        }

        System.out.println("Sorted Map......");
        Map<String,String> sortedMap=sortByComparator(unsortMap);

        for (Map.Entry entry : sortedMap.entrySet())
        {
    System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
        }
   }

   private static Map sortByComparator(Map unsortMap)
   {
        List list=new LinkedList(unsortMap.entrySet());
        //sort list based on comparator
        Collections.sort(list,new Comparator()
        {
             public int compare(Object o1,Object o2)
             {
     return ((Comparable)((Map.Entry)(o2)).getKey()).compareTo(((Map.Entry) (o1)).getKey());
             }
        });

        //put sorted list into map again
    Map sortedMap=new LinkedHashMap();
    for (Iterator it=list.iterator();it.hasNext();)
    {
         Map.Entry entry=(Map.Entry)it.next();
         sortedMap.put(entry.getKey(),entry.getValue());
    }
    return sortedMap;
   }   
}

Output:
Unsort Map......
Key : 3 Value : d
Key : 2 Value : A
Key : 1 Value : D
Key : 7 Value : b
Key : 6 Value : c
Key : 5 Value : C
Key : 4 Value : B
Key : 8 Value : a
Sorted Map......
Key : 8 Value : a
Key : 7 Value : b
Key : 6 Value : c
Key : 5 Value : C
Key : 4 Value : B
Key : 3 Value : d
Key : 2 Value : A
Key : 1 Value : D

sorting a hashmap in java by key

//sorting a hashmap in java by key
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class SortMapExample
{
   public static void main(String[] args)
   {
    Map<String,String> unsortMap=new HashMap<String,String>();
    unsortMap.put("2", "A");
    unsortMap.put("4", "B");
    unsortMap.put("1", "D");
    unsortMap.put("6", "c");
    unsortMap.put("3", "d");
    unsortMap.put("5", "C");
    unsortMap.put("7", "b");
    unsortMap.put("8", "a");
    System.out.println("Unsort Map......");
   
        for(Map.Entry entry : unsortMap.entrySet())
        {
            System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
        }

        System.out.println("Sorted Map......");
        Map<String,String> sortedMap=sortByComparator(unsortMap);

        for (Map.Entry entry : sortedMap.entrySet())
        {
            System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
        }
   }

   private static Map sortByComparator(Map unsortMap)
   {
        List list=new LinkedList(unsortMap.entrySet());
        //sort list based on comparator
        Collections.sort(list,new Comparator()
        {
             public int compare(Object o1,Object o2)
             {
               return ((Comparable)((Map.Entry)(o1)).getKey()).compareTo(((Map.Entry) (o2)).getKey());
             }
        });

        //put sorted list into map again
    Map sortedMap=new LinkedHashMap();
    for (Iterator it=list.iterator();it.hasNext();)
    {
         Map.Entry entry=(Map.Entry)it.next();
         sortedMap.put(entry.getKey(),entry.getValue());
    }
    return sortedMap;
   }   
}

Output:
Unsort Map......
Key : 3 Value : d
Key : 2 Value : A
Key : 1 Value : D
Key : 7 Value : b
Key : 6 Value : c
Key : 5 Value : C
Key : 4 Value : B
Key : 8 Value : a
Sorted Map......
Key : 1 Value : D
Key : 2 Value : A
Key : 3 Value : d
Key : 4 Value : B
Key : 5 Value : C
Key : 6 Value : c
Key : 7 Value : b
Key : 8 Value : a

sorting a hashmap in java by value

//sorting a hashmap in java by value
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class SortMapExample
{
   public static void main(String[] args)
   {
    Map<String,String> unsortMap=new HashMap<String,String>();
    unsortMap.put("1", "D");
    unsortMap.put("2", "A");
    unsortMap.put("3", "d");
    unsortMap.put("4", "B");
    unsortMap.put("5", "C");
    unsortMap.put("6", "c");
    unsortMap.put("7", "b");
    unsortMap.put("8", "a");
    System.out.println("Unsort Map......");
   
        for(Map.Entry entry : unsortMap.entrySet())
        {
            System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
        }

        System.out.println("Sorted Map......");
        Map<String,String> sortedMap=sortByComparator(unsortMap);

        for (Map.Entry entry : sortedMap.entrySet())
        {
            System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
        }
   }

   private static Map sortByComparator(Map unsortMap)
   {
        List list=new LinkedList(unsortMap.entrySet());
        //sort list based on comparator
        Collections.sort(list,new Comparator()
        {
             public int compare(Object o1,Object o2)
             {
               return ((Comparable)((Map.Entry)(o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue());
             }
        });

        //put sorted list into map again
    Map sortedMap=new LinkedHashMap();
    for (Iterator it=list.iterator();it.hasNext();)
    {
         Map.Entry entry=(Map.Entry)it.next();
         sortedMap.put(entry.getKey(),entry.getValue());
    }
    return sortedMap;
   }   
}

Output:
Unsort Map......
Key : 3 Value : d
Key : 2 Value : A
Key : 1 Value : D
Key : 7 Value : b
Key : 6 Value : c
Key : 5 Value : C
Key : 4 Value : B
Key : 8 Value : a
Sorted Map......
Key : 2 Value : A
Key : 4 Value : B
Key : 5 Value : C
Key : 1 Value : D
Key : 8 Value : a
Key : 7 Value : b
Key : 6 Value : c
Key : 3 Value : d

HashMap in java Example

HashMap implements Map and extends AbstractMap. It keeps the data in the key and value form. An object of HashMap does not allow key values as duplicates. We can not determine in which order HashMap object displays the data. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read by an iterator.
 
The following constructors are defined:
HashMap( )
HashMap(Map m)
HashMap(int capacity)
HashMap(int capacity, float fillRatio)
 
The first form constructs a default hash map.
The second form initializes the hash map by using the elements of m. The third form initializes the capacity of the hash map to capacity. The fourth form initializes both the capacity and fill ratio of the hash map by using its arguments.

HashMap doesnot have iterator method. So use the entrySet() method to get the data in Set object form.

import java.util.*;

public class hashmap {
        public static void main(String[] args) {
                HashMap hash = new HashMap();
                hash.put("roll", new Integer(10));
                hash.put("name", "Sathya");
                hash.put("age", 22);
                Set s = hash.entrySet();
                Iterator i = s.iterator();
                while (i.hasNext()) {
                System.out.println(i.next());
                }
        }
}

Output:
roll=10 age=22 name=Sathya

Sort LinkedList In Descending Order Example

/* Sort LinkedList In Descending Order Example, sorting linked list java example, sorting linked list java alphabetically, sorting linked list java code, How to sort LinkedList using Comparator */ 

    import java.util.LinkedList;
    import java.util.Collections;
    import java.util.Comparator;
     
    public class SortLinkedListExample 
    {
      public static void main(String[] args) 
      {       
        //create an java.util.LinkedList object
        java.util.LinkedList ll = new java.util.LinkedList();
       
        //Add elements to LinkedList
        ll.add("A");
        ll.add("B");
        ll.add("C");
        ll.add("D");
        ll.add("E");
       
        /*
       To get comparator that imposes reverse order on a Collection use
    static java.util.Comparator reverseOrder() method of java.util.Collections class
        */       
        java.util.Comparator comparator = java.util.Collections.reverseOrder();       
        System.out.println("Before sorting LinkedList in descending order: "+ll);       
        /*
       To sort an LinkedList using comparator use,
    static void sort(java.util.List list,java.util.Comparator c) method of java.util.Collections class.
        */       
        java.util.Collections.sort(ll,java.util.comparator);
        System.out.println("After sorting LinkedList in descending order: "+ll);
       
      }
    }
     
    Output:
    Before sorting LinkedList in descending order: [A, B, C, D, E]
    After sorting LinkedList in descending order: [E, D, C, B, A]

Sorting LinkedList in java example

import java.util.LinkedList;
import java.util.Collections;
 
public class LinkedListSort {
    public static void main(String[] args) {
        LinkedList<String> ranks = new LinkedList<String>();
        ranks.add("5");
        ranks.add("3");
        ranks.add("1");
        ranks.add("6");
        ranks.add("2");
        ranks.add("4");
 
        System.out.println("Before sorting:");
        System.out.println("===============");
        for (String rank : ranks) {
            System.out.println("rank = " + rank);
        }
 
        //
        // Sort the elements of linked list based on its data
        // natural order.
        //
        Collections.sort(ranks);
 
        System.out.println("After sorting:");
        System.out.println("===============");
        for (String rank : ranks) {
            System.out.println("rank = " + rank);
        }
    }
}

The result of the program are:

Before sorting:
===============
rank = 5
rank = 3
rank = 1
rank = 6
rank = 2
rank = 4
After sorting:
===============
rank = 1
rank = 2
rank = 3
rank = 4
rank = 5
rank = 6

LinkedList in java with example

The LinkedList class extends AbstractSequentialList. This AbstractSequentialList class extends AbstractList.AbstractList implements the List interface. LinkedList class finally implements the List interface. LinkedList class has the two constructors;
1.LinkedList()
ex: LinkedList ll=new LinkedList();

2.LinkedList(Collection c)

The first constructor builds an empty linked list.
The second constructor builds a linked list that is initialized with the elements of the collection c.

The LinkedList class defines some useful methods of its own for manipulating and accessing lists.

To add elements to the start of the list, use
public void addFirst(Object o)
ex: ll.addFirst(new Integer(10));

To add elements to the end, use
public void addLast(Object o)
Here, 'o' is the item being added.
ex: ll.addLast(new Integer(10));

To obtain the first element, use
public Object getFirst()
ex: Object o= ll.getFirst();

To obtain the last element, use
public Object getLast()
ex: Object o= ll.getLast();

To remove the first element, use
public Object removeFirst()
ex: Object o= ll.removeFirst();

To remove the last element, use
public Object removeLast()
ex: Object o= ll.removeLast();

To insert items at a specific location, use
public void add(int, Object)
ex: ll.add(1, "A2")

To get items at a specific location, use
public Object get(int)
ex: Object o=ll.get(1);

To remove items at a specific location, use
public Object remove(int)
ex: Object o=ll.remove(1);


import java.util.*;

public class LinkedListExample
  {
  public static void main(String[] args)
  {
  System.out.println("Linked List Example!");
  LinkedList list = new LinkedList();
  int size;
  Iterator iterator;
  //Adding data in the list
  list.add(new Integer(11));
  list.add(new Integer(22));
  list.add(new Integer(33));
  list.add(new Integer(44));
  size = list.size();
  System.out.print( "Linked list data: "); 
  //Create a iterator
  iterator = list.iterator();
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" "); 
  }
  System.out.println();
  //Check list empty or not
  if (list.isEmpty()){
  System.out.println("Linked list is empty");
  }
  else{
  System.out.println( "Linked list size: " + size);
  }
  System.out.println("Adding data at 1st location: 55");
  //Adding first
  list.addFirst(new Integer(55));
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" "); 
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  System.out.println("Adding data at last location: 66");
  //Adding last or append
  list.addLast(new Integer(66));
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" "); 
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  System.out.println("Adding data at 3rd location: 99");
  //Adding data at 3rd position
  list.add(2,new Integer(99));
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" "); 
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  //Retrieve first data
  System.out.println("First data: " + list.getFirst());
  //Retrieve lst data
  System.out.println("Last data: " + list.getLast());
  //Retrieve specific data
  System.out.println("Data at 4th position: " + list.get(3));
  //Remove first
  int first = list.removeFirst();
  System.out.println("Data removed from 1st location: " + first);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  //After removing data
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" "); 
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  //Remove last
  int last = list.removeLast();
  System.out.println("Data removed from last location: " + last);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  //After removing data
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" "); 
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  //Remove 2nd data
  int second = list.remove(1);
  System.out.println("Data removed from 2nd location: " + second);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  //After removing data
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" "); 
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  //Remove all
  list.clear();
  if (list.isEmpty()){
  System.out.println("Linked list is empty");
  }
  else{
  System.out.println( "Linked list size: " + size);
  }
  }
}

Output:
LinkedListExample
Linked List Example!
Linked list data: 11 22 33 44
Linked list size: 4
Adding data at 1st location: 55
Now the list contain: 55 11 22 33 44
Now the size of list: 5
Adding data at last location: 66
Now the list contain: 55 11 22 33 44 66
Now the size of list: 6
Adding data at 3rd location: 55
Now the list contain: 55 11 99 22 33 44 66
Now the size of list: 7
First data: 55
Last data: 66
Data at 4th position: 22
Data removed from 1st location: 55
Now the list contain: 11 99 22 33 44 66
Now the size of list: 6
Data removed from last location: 66
Now the list contain: 11 99 22 33 44
Now the size of list: 5
Data removed from 2nd location: 99
Now the list contain: 11 22 33 44
Now the size of list: 4
Linked list is empty

17 Sept 2012

java policy file creation example


/* AUTOMATICALLY GENERATED ON Sun Dec 09 12:09:03 IST 2012*/
/* DO NOT EDIT */

grant {
  permission java.security.AllPermission;
};

Set Password Symbol example in java


import javax.swing.JPasswordField;  
import javax.swing.JFrame;  
  
import java.awt.FlowLayout;  
  
public class SetPasswordSymbol  
{  
public static void main(String[]args)  
{  
 //Create a password field with number of columns equal to 10  
 JPasswordField passwordField=new JPasswordField(10);  
  
 //Set password symbol  
 //In my case i use *  
 //You can change for what you want.But make sure it is only one character  
 //This is because, method setEchoChar receive only one character  
 passwordField.setEchoChar('*');  
  
  
 //Create a JFrame with title ( Set Password Symbol )  
 JFrame frame=new JFrame("Set Password Symbol");  
  
 //Set JFrame layout to FlowLayout  
 frame.setLayout(new FlowLayout());  
  
 //Add password field into JFrame  
 frame.add(passwordField);  
  
 //Set default close operation for JFrame  
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  
 //Set JFrame size to :  
 //WIDTH : 300 pixels  
 //HEIGHT : 65 pixels  
 frame.setSize(300,65);  
  
 //Make JFrame visible. So we can see it  
 frame.setVisible(true);  
}  
}  

Set JTextArea Background Color in java


import javax.swing.JTextArea;  
import javax.swing.JFrame;  
import java.awt.Color;  
  
public class SetJTextAreaBackgroundColor  
{  
public static void main(String[]args)  
{  
 //Create text area using JTextArea  
 JTextArea textArea=new JTextArea();  
  
 //Create JFrame with title ( Set JTextArea background color )  
 JFrame frame=new JFrame("Set JTextArea background color");  
  
 //Set color base on RGB  
 //You can get RGB value for your color at "Color picker" at above  
 //R=255  
 //G=0  
 //B=0  
 Color color=new Color(255,0,0);  
  
 //Set JTextArea background color to color that you choose  
 textArea.setBackground(color);  
  
 //Add JTextArea into JFrame  
 frame.add(textArea);  
  
 //Set default close operation for JFrame  
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  
 //Set JFrame size  
 frame.setSize(500,300);  
  
 //Make JFrame visible  
 frame.setVisible(true);  
}  
}  

Set JPasswordField Background Color in java swings


import javax.swing.JPasswordField;  
import javax.swing.JFrame;  
import java.awt.Color;  
  
public class SetJPasswordFieldBackgroundColor  
{  
public static void main(String[]args)  
{  
 //Create password field with number of columns equal to 10  
 JPasswordField passwordField=new JPasswordField(10);  
  
 //Create JFrame with title ( Set JPasswordField background color )  
 JFrame frame=new JFrame("Set JPasswordField background color");  
  
 //Set color base on RGB  
 //You can get RGB value for your color at "Color picker" at above  
 //R=255  
 //G=0  
 //B=0  
 Color color=new Color(255,0,0);  
  
 //Set JPasswordField background color to color that you choose  
 passwordField.setBackground(color);  
  
 //Add JPasswordField into JFrame  
 frame.add(passwordField);  
  
 //Set default close operation for JFrame  
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  
 //Set JFrame size  
 frame.setSize(500,65);  
  
 //Make JFrame visible  
 frame.setVisible(true);  
}  
}