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

Wednesday, August 10, 2011

Sort Java Vector in descending order using comparator

package org.best.example;
   
    /*
      Sort Java Vector in descending order using comparator example
      This java example shows how to sort elements of Java Vector in descending order
      using comparator and reverseOrder method of Collections class.
    */
    
    import java.util.Vector;
    import java.util.Collections;
    import java.util.Comparator;
    
    public class SortVectorInDescendingOrderExample {
    
    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 would be
    Before sorting Vector in descending order : [1, 2, 3, 4, 5]
    After sorting Vector in descending order : [5, 4, 3, 2, 1]
    */

Monday, July 25, 2011

Hash Set Example

    package org.best.example;

    /*
      Simple Java HashSet example
      This simple Java Example shows how to use Java HashSet. It also describes how to
      add something to HashSet object using add method.
    */
   
    import java.util.HashSet;
   
    public class SimpleHashSetExample {
   
    public static void main(String[] args) {
    //create object of HashSet
    HashSet hSet = new HashSet();
   
    /*
      Add an Object to HashSet using
      boolean add(Object obj) method of Java HashSet class.
      This method adds an element to HashSet if it is not already present in HashSet.
      It returns true if the element was added to HashSet, false otherwise.
      */
   
    hSet.add(new Integer("1"));
    hSet.add(new Integer("2"));
    hSet.add(new Integer("3"));
   
    /*
      Please note that add method accepts Objects. Java Primitive values CAN NOT
      be added directly to HashSet. It must be converted to corrosponding
      wrapper class first.
      */
   
    System.out.println("HashSet contains.." + hSet);
    }
    }
   
    /*
    Output of the program would be
    HashSet contains..[3, 2, 1]
    */

Sunday, July 24, 2011

Get Head Set from Java TreeSet

    /*
      Get Head Set from Java TreeSet example
      This Java Example shows how to get the portion of TreeSet containing the values
      less than the specified value using headSet method of Java TreeSet class.
    */
    package org.best.example;
    import java.util.SortedSet;
    import java.util.TreeSet;
    
    public class GetHeadSetFromTreeSetExample {
    
    public static void main(String[] args) {
    
    //create TreeSet object
    TreeSet tSet = new TreeSet();
    
    //add elements to TreeSet
    tSet.add("1");
    tSet.add("3");
    tSet.add("2");
    tSet.add("5");
    tSet.add("4");
    
    /*
      To get a Head Set from Java TreeSet use,
      SortedSet headSet(Object fromElement) method of Java TreeSet class.
    
      This method returns the portion of TreeSet containing elements less than
      fromElement.
    
      Please note that, the SortedSet returned by this method is backed by
      the original TreeSet. So any changes made to SortedSet will be
      reflected back to original TreeSet.
      */
    
    SortedSet sortedSet = tSet.headSet("3");
    
    System.out.println("Head Set Contains : " + sortedSet);
    
    }
    }
    
    /*
    Output would be
    Head Set Contains : [1, 2]
    */

Saturday, July 23, 2011

Copy all elements of Java TreeSet to an Object Array

    /*
      Copy all elements of Java TreeSet to an Object Array Example
      This Java Example shows how to copy all elements of Java TreeSet object to an
      array of Objects using toArray method.
    */
    
    package org.best.example;
    import java.util.TreeSet;
    
    public class CopyElementsOfTreeSetToArrayExample {
    
    public static void main(String[] args) {
    
    //create object of TreeSet
    TreeSet tSet = new TreeSet();
    
    //add elements to TreeSet object
    tSet.add(new Integer("1"));
    tSet.add(new Integer("2"));
    tSet.add(new Integer("3"));
    
    /*
      To copy all elements of java TreeSet object into array use
      Object[] toArray() method.
      */
    
    Object[] objArray = tSet.toArray();
    
    //display contents of Object array
    System.out.println("TreeSet elements are copied into an Array.
    Now Array Contains..");
    for(int index=0; index < objArray.length ; index++)
    System.out.println(objArray[index]);
    }
    }
    
    /*
    Output would be
    TreeSet elements are copied into an Array. Now Array Contains..
    1
    2
    3
    */

Friday, July 22, 2011

Particular value exists in Java TreeSet

    /*
      Check if a particular value exists in Java TreeSet example
      This Java Example shows how to check if TreeSet object contains a particular
      value using contains method of TreeSet class.
    */
     package org.best.example;
    import java.util.TreeSet;
    
    public class CheckValueOfTreeSetExample {
    
    public static void main(String[] args) {
    
    //create TreeSet object
    TreeSet tSet = new TreeSet();
    
    //add elements to TreeSet
    tSet.add("1");
    tSet.add("3");
    tSet.add("2");
    tSet.add("5");
    tSet.add("4");
    
    /*
      To check whether a particular value exists in TreeSet use
      boolean contains(Object value) method of TreeSet class.
      It returns true if the TreeSet contains the value, otherwise false.
      */
    
    boolean blnExists = tSet.contains("3");
    System.out.println("3 exists in TreeSet ? : " + blnExists);
    }
    }
    
    /*
    Output would be
    3 exists in TreeSet ? : true
    */

Thursday, July 21, 2011

Enumerate through a Vector using Java Enumeration Example

/*
Enumerate through a Vector using Java Enumeration Example
This Java Example shows how to enumerate through elements of a Vector
using Java Enumeration.
*/

package org.best.example;
import java.util.Vector;
import java.util.Enumeration;

public class EnumerateThroughVectorExample {

public static void main(String[] args) {

//create a Vector object

Vector v = new Vector();

//populate the Vector

v.add("One");
v.add("Two");
v.add("Three");
v.add("Four");

//Get Enumeration of Vector's elements using elements() method

Enumeration e = v.elements();

/*
Enumeration provides two methods to enumerate through the elements.
It's hasMoreElements method returns true if there are more elements to
enumerate through otherwise it returns false. Its nextElement method returns
the next element in enumeration.
*/

System.out.println("Elements of the Vector are : ");

while(e.hasMoreElements())
         System.out.println(e.nextElement());
}

}
/*
Output would be
Elements of the Vector are :
One
Two
Three
Four
*/

Saturday, July 2, 2011

How to Remove Duplicates from HashSet

package org.best.example;

import java.util.*;

 public class HashSetTest
 {
     private String colors[] = { "red", "white", "blue",
     "green", "gray", "orange",
     "tan", "white", "cyan",
     "peach", "gray", "orange" };

     public HashSetTest()
     {
         ArrayList aList;

         aList = new ArrayList( Arrays.asList( colors ) );
         System.out.println( "ArrayList: " + aList );
         printNonDuplicates( aList );
     }

     public void printNonDuplicates( Collection c )
     {
         HashSet ref = new HashSet( c ); // create a HashSet
         Iterator i = ref.iterator(); // get iterator

         System.out.println( "\nNonduplicates are: " );
         while ( i.hasNext() )
             System.out.print( i.next() + " " );

         System.out.println();
     }

     public static void main( String args[] )
     {
         new HashSetTest();
     }
 }

Saturday, June 18, 2011

How to loop a Map in Java

Here’s few ways to loop or iterate a Map or HashMap in Java.

package org.best.example.collection;
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
 
public class LoopAMap{
 
   public static void main(String[] args) {
 
 //initial a Map
 Map<String,String> map = new HashMap<String,String>();
 map.put("1", "Jan");
 map.put("2", "Feb");
 map.put("3", "Mar");
 map.put("4", "Apr");
 map.put("5", "May");
 map.put("6", "Jun");
 
 //Map -> Set -> Iterator -> Map.Entry -> troublesome
        Iterator iterator=map.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry mapEntry=(Map.Entry)iterator.next();
            System.out.println("The key is: "+mapEntry.getKey()
              + ",value is :"+mapEntry.getValue());
        }
 
        //more elegant way
        for (Map.Entry<String, String> entry : map.entrySet()) {
         System.out.println("Key : " + entry.getKey() 
          + " Value : " + entry.getValue());
        }
 
        //weired way, but work anyway
        for (Object key: map.keySet()) {
         System.out.println("Key : " + key.toString() 
          + " Value : " + map.get(key));
        }
 
   }
 
}

Thursday, June 16, 2011

How to Use HashMap in Java

The HashMap class uses a hash table to implement the Map interface. This allows the execution time of basic operations, such as get() and put(), to remain constant even for large sets.
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. The meaning of capacity and fill ratio is the same as for HashSet, described earlier.
HashMap implements Map and extends AbstractMap. It does not add any methods of its own. You should note that a hash map does not guarantee the order of its elements. 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 program illustrates HashMap. It maps names to account balances. Notice how a set-view is obtained and used.

package org.best.example;

import java.util.*;
class HashMapDemo {
public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Todd Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));
// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account
double balance = ((Double)hm.get("John Doe")).doubleValue();
hm.put("John Doe", new Double(balance + 1000));
System.out.println("John Doe's new balance: " +
hm.get("John Doe"));
}
}

Output from this program is shown here:

Ralph Smith: -19.08
Tom Smith: 123.22
John Doe: 3434.34
Todd Hall: 99.22
Jane Baker: 1378.0
John Doe's current balance: 4434.34
The program begins by creating a hash map and then adds the mapping of names to balances. Next, the contents of the map are displayed by using a set-view, obtained by calling entrySet(). The keys and values are displayed by calling the getKey() and getValue() methods that are defined by Map.Entry. Pay close attention to how the deposit is made into John Doe's account. The put() method automatically replaces any preexisting value that is associated with the specified key with the new value. Thus, after John Doe's account is updated, the hash map will still contain just one "John Doe" account.