Showing posts with label map-implementation. Show all posts
Showing posts with label map-implementation. Show all posts

Saturday, 28 May 2011

The Properties class in java

The Properties class inherits from Hashtable and is part of JDK 1.0. Instances of Properties typically represent persistent values describing something such as system settings. For example, the System.getProperties() method returns a system properties table with various key/value pairs that describe the platform the program is running on.

The Properties class adds additional functionality that can be extremely useful. The Properties class represents a persistent list of properties. What exactly does this mean? The Properties class is designed to provide methods to store and load files containing key-value pairs as Strings. Properties files are simply key-value pairs where the key and value are separated by an "=" (name=Tom) and eack key-value pair is on a separate line. A Windows ini file is an example of a properties file. In many cases, XML files are replacing properties files but the simplicity of a properties file combined with its ease of use makes the Properties class still a very useful class.

Although the Properties file inherits the methods of the Hashtable, it is recommended that the Hashtable put method not be used as this may allow the insertion of non-String objects. Only Strings should be used as either a key or a value in a Properties object. A Properties object with a non-String in it will throw an exception if you attempt to store it to a file. A Properties object can contain another Properties object (specified in the constructor) which is used as the default keys if no matching key is found in the Properties object.

Methods in Property class

The Properties class provides several new methods:

  • Object setProperty(String key, String value) - Invokes the Hashtable put method. Although it returns an Object, the return should always be a String.
  • String getProperty(String key) - Returns the value found for the matching key. Null if no match is found.
  • String getProperty(String key, String defaultValue) - Returns the value found for the matching key.The defaultValue is returned if no match is found.
  • void list(PrintStream output) - Writes the Properties object out to the specified PrintStream.
  • void list(PrintWriter output) - Writes the Properties object out to the specified PrintWriter.
  • void load(InputStream input) - Loads data into the Properties object using the specified InputStream.Key-value pairs are assumed to be on separate lines and each kei is separated from its value by an equals sign ("="). In addition to the equals sign, a colon (":") or the first white space will be used as a separator when reading in a properties file.
  • void store(OutputStream output, String header) - Writes the Properties object out to the specified OutputStream. The header is written as a comment line at the beginning of the file. After the header line, another comment line is written containing the current date and time. A "#" is placed at the beginning of these lines to identify them as comments. The OutputStream will be flushed but will remain open. Any properties in the default Properties object are not written to the output.

Example of Properties class in java

Property class example in java

Here is an example of reading in a properties file, removing the password and printing out the reminder.
import java.util.*;
import java.io.*;

public class PropertyDemo {

public static void main(String[] args)
throws Exception {

BufferedInputStream bStream = new BufferedInputStream
(new FileInputStream("prefs.ini"));
Properties props = new Properties();
props.load(bStream);
props.remove("password");
props.list(System.out);
bStream.close();
}
}

LinkedHashMap in java

New to J2SE 1.4, the LinkedHashMap class is used in exactly the same way as the HashMap class. It has no additional methods but it does have one additional constructor that we will discuss in a moment. The basic difference between HashMap and LinkedHashMap is that the LinkedHashMap maintains the order of the items added to the Map. It does this by maintaining a doubly linked list containing the hash and the original order of the items. According to Sun, the LinkedHashMap should run nearly as fast as the HashMap.

The LinkedHashMap has one additional constructor that takes an additional boolean parameter. This allows you to construct a LinkedHashMap that maintains items, not in the order that they are added to the Map but rather in the order in which they are accessed.

Example of LinkedHashMap

LinkedHashMap example in java

This example shows LinkedHashMap in java:

public class JavaLinkedHashMapExample {
public static void main(String[] args) {
//create object of LinkedHashMap
LinkedHashMap lHashMap = new LinkedHashMap();
//put the values
lHashMap.put("One", new Integer(1));
lHashMap.put("Two", new Integer(2));
//get the value
Object obj = lHashMap.get("One");
System.out.println(obj);
//iterate over linked hash map values
Collection c = lHashMap.values();

//obtain an Iterator for Collection
Iterator itr = c.iterator();



//iterate through LinkedHashMap values iterator
while(itr.hasNext())
System.out.println(itr.next());
}
}

The IdenitityHashMap Class in java

The IdentityHashMap is also like the HashMap with the exception that a key is considered equal to another key only if they are pointing to the exact same object. Other implementations of Map use the equals( ) method to determine if two keys are equal. The IdentityHashMap uses the == comparator. Two keys (a and b) are considered equal if a == b. The IdentityhashMap should only be used in the cases where this functionality is required. It should not be used otherwise.

HashTable in java

Hashtable was part of the original java.util and is a concrete implementation of a Dictionary. However, Java 2 reengineered Hashtable so that it also implements the Map interface. Thus, Hashtable is now integrated into the collections framework. It is similar to HashMap, but is synchronized.

Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.

A hash table can only store objects that override the hashCode() and equals() methods that are defined by Object. The hashCode() method must compute and return the hash code for the object. Of course, equals() compares two objects. Fortunately, many of Java's built-in classes already implement the hashCode() method. For example, the most common type of Hashtable uses a String object as the key. String implements both hashCode() and equals().

Constructors of HashTable class

Hashtable( )
Hashtable(int size)
Hashtable(int size, float fillRatio)
Hashtable(Map m)

 

The first version is the default constructor. The second version creates a hash table that has an initial size specified by size. The third version creates a hash table that has an initial size specified by size and a fill ratio specified by fillRatio. This ratio must be between 0.0 and 1.0, and it determines how full the hash table can be before it is resized upward. Specifically, when the number of elements is greater than the capacity of the hash table multiplied by its fill ratio, the hash table is expanded. If you do not specify a fill ratio, then 0.75 is used. Finally, the fourth version creates a hash table that is initialized with the elements in m. The capacity of the hash table is set to twice the number of elements in m. The default load factor of 0.75 is used. The fourth constructor was added by Java 2.

 

Examples on HashTable


Friday, 27 May 2011

TreeMap in Java Collections

The TreeMap class guarantees that the keys in the Map will be sorted in ascending order by either the keys natural order or by a Comparator provided to the constructor of the TreeMap. TreeMap implements Map and SortedSet interfaces and extends AbstractMap. TreeMap keeps the balanced binary tree in sorted order by key.

Searching for an item in a TreeMap will be slower than in a HashMap because the hashing algorithm gives better performance than the compareTo() method which is used to locate items in a TreeMap.

 

Creating a TreeMap – Constructors for TreeMap

It has the following constructors. Here comp stands for Comparator, mp stands for Map, smp stands for SortedMap.

Result Constructor Description
tmap = new TreeMap() Creates new TreeMap. Keys sorted by natural order.
tmap = new TreeMap(comp) Creates new TreeMap using Comparator comp to sort keys.
tmap = new TreeMap(mp) Creates new TreeMap from Map mp using natural ordering.
tmap = new TreeMap(smp) Creates new TreeMap from SortedMap smp using key ordering from smp.


 

Methods in TreeMap

TreeMap adds the methods from Map and SortedMap. See the methods of these interfaces – Methods in Map interface, Methods in SortedMap interface.

So other than Map interface methods it has SortedMap interface Methods:

  • Object firstKey() - Gets the first key from the sorted Map.
  • Object lastKey() - Gets the last key from the sorted map.
  • SortedMap headMap(Object toKey) - Returns a view of the portion of this Map whose keys are less than toKey.
  • SortedMap tailMap(Object fromKey) - Returns a view of the portion of this Map whose keys are greater than or equal to fromKey.
  • SortedMap subMap(Object fromKey, Object toKey) - Returns a view of the portion of this Map whose starting key is greater than or equal to fromKey and whose ending key is less than toKey.

 

Example

TreeMap Example in java

Hashmap Tutorial

The HashMap class is the simplest implementation of the Map interface. The HashMap does not add any additional methods (other than clone) beyond those found in the Map interface.

Creating the HashMap in java

In addition to implemented the Map interface methods, HashMap has the following constructors.
Result Constructor Description
hmap = new HashMap() Creates a new HashMap with default initial capacity 16 and load factor 0.75.
hmap = new HashMap(initialCapacity) Creates a new HashMap with the specified initial int capacity.
hmap = new HashMap(initialCapacity, loadFactor) Creates a new HashMap with the specified capacity which will not exceed a specified (float) load factor.
hmap = new HashMap(mp) Creates a new HashMap with elements from the Map mp

 

Performance of the HashMap

The HashMap achieves good performance by using a hash to store the key in the Map. The hash allows fast lookup which means that the containKey( ) method will perform much better than the containsValue( ) method.
HashMaps will automatically grow when you add too many elements. However, growing requires copying, rehashing and rechaining, which affects its overall performance.
Performance of HashMap depends on two important factors that are
  • Initial Capacity and
  • Load Factor
Initial Capacity is the capacity at the time the HashMap is created. Load factor determines when to increase the capacity of the HashMap. The default load factor is 0.75.
Important Note: The initial capacity is not the actual number of elements you plan to store in HashMap. Say for example, if you set initial capacity of 100 and the load factor is 0.75, then the capacity of HashMap will be automatically increased when it reaches to 75 not 100.
Any Object used as a key in a HashMap must implement the hashCode( ) and equals( ) methods. See Part 2 of this series for a discussion of this issue.
The HashMap does not guarantee the order of the items in the Map and allows one null key. Duplicates are not permitted. The HashSet offers "constant time" performance for lookups involving the key and linear time for lookups based on value. This means that adding items to the Map will not cause significant performance degradation as long as lookups are done by the key. The performance of basic functions such as put, remove, get, etc is based on two factors which can be specified in the constructor of the HashMap, initial capacity and load factor.


Methods in HashMap

It inherits all the methods from Map and adds following method.
  • Object clone(): Returns a copy of the HashMap. The cloned object contains the same key/value pairs.
 So see – Map interface methods.

Example

Creating a HashMap in Java
Iterating over hashmap
Sorting a hashmap

Map implementations in java

A number of classes implement the Map interface, including HashMap, TreeMap, LinkedHashMap, WeakHashMap, ConcurrentHashMap, and Properties. The most generally useful class is HashMap.
  • java.util.HashMap is implemented with a hash table. Access time is O(1). Entries are unsorted.
    – similar to HashTable but allows null keys and values
    – not thread safe
  • java.util.LinkedHashMap is implemented with a hash table. Access time is O(1). Entries are sorted in either entry order or order of last access, which is useful for implementing a LRU (least recently used) caching policy.
  • java.util.TreeMap is implemented as a balanced binary tree. Access time is O(log N). Entries are sorted. 
  • java.util.HashTable(old classes)
    – updated class from earlier Java versions
    – does not allow null keys or values
    – thread safe
  • java.util.WeakHashMap -
    – like HashMap
    – entry is automatically removed from HashMap if no more "ordinary" references to key
  • java.util.IdentityHashMap
  • java.util.EnumMap
  • java.util.Properties

Saturday, 14 May 2011

Performance of Map interface implementations

Hashtable

An instance of Hashtable has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. Note that the hash table is open: in the case of a "hash collision", a single bucket stores multiple entries, which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. The initial capacity and load factor parameters are merely hints to the implementation. The exact details as to when and whether the rehash method is invoked are implementation-dependent.

HashMap

This implementation provides constant-time [ Big O Notation is O(1) ] performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.
Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

 

TreeMap

The TreeMap implementation provides guaranteed log(n) [ Big O Notation is O(log N) ] time cost for the containsKey, get, put and remove operations.

 

LinkedHashMap

A linked hash map has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashMap. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashMap, as iteration times for this class are unaffected by capacity.

Monday, 29 November 2010

Iterate through values of Java Hashtable example

This example shows how to iterate over hash table using enumerator:

//create Hashtable object    
Hashtable ht = new Hashtable();
//add key value pairs to Hashtable
ht.put("1","One");
ht.put("2","Two");
ht.put("3","Three");
//get Enumeration of values contained in Hashtable using
//Enumeration elements() method of Hashtable class
Enumeration e = ht.elements();
//iterate through Hashtable values Enumeration
while(e.hasMoreElements())
System.out.println(e.nextElement());

Monday, 20 September 2010

Hashtable example in java

Here we will take example of hash table class in java. To jump to full example jump here.

Creating the hash table:

//Creating hashtable with default initial capacity
HashTable hashtable= new HashTable();
//To specify initial capacity,use following constructor.
Hashtable hashtable = new Hashtable(100);
//To create hashtable from map use following constructor
Hashtable hashtable = new Hashtable(Map myMap);


Putting the values


For this put method is used. Eg.


hastable.put("One",new Integer(1));


To copy all key - value pairs from Map to Hashtable use putAll method.Signature of putAll method is, void putAll(Map m).


Getting the values


Use get method of Hashtable to get value mapped to particular key.Signature of the get method is,

Object get(Object key)


Removing the elements



To remove elements from hashtable use remove method.Signature of remove methid is, 


Object remove(Object key)

This method returns value that had mapped to the given key, otherwise null if mapping not found.         


//To remove particular key - value pair 
//from the Hashtable use remove method.
hashtable.remove("One");

 

To check if hashtable is empty or not

To check whether Hashtable is empty or not, use isEmpty() method.isEmpty() returns true is Hashtable is empty, otherwise false.


To check if element exists:


Finding particular value from the Hashtable : Hashtable's contains method returns boolean depending upon the presense of the value in given hashtable.Signature of the contains method is,


boolean contains(Object value) 


To check if key exists


Finding particular Key from the Hashtable : Hashtable's containsKey method returns boolean depending upon the presense of the key in given hashtable.Signature of the method is, boolean containsKey(Object key)


Iterating over hash table



Iterating over keys

To get all keys stored in Hashtable use keys method.Signature of the keys method is,Enumeration keys()To get Set of the keys use keySet() method instead.Set keySet()


Iterating over values


To get all values stored in Hashtable use elements method. Signature of the elements method is, Enumeration elements() To get Set of the values use entrySet() method instead.


Full Code Example of Hashtable



import java.util.Hashtable;
import java.util.Enumeration;
public class HashtableExample{
public static void main(String args[]){
// constructs a new empty hashtable
//with default initial capacity
Hashtable hashtable = new Hashtable();


//Puting the values in hashTable
hashtable.put( "One", new Integer(1) ); // adding value into hashtable
hashtable.put( "Two", new Integer(2) );
hashtable.put( "Three", new Integer(3) );
/*
We CAN NOT add primitives to the hashtable.

*We have to wrap it into one of the wrapper before adding.
*/
//get number of keys present in the hashtable
System.out.println("Hashtable contains " + hashtable.size() + " key value pair.");

if( hashtable.contains( new Integer(1) ) ){
System.out.println("Hashtable contains 1 as value");
}else{
System.out.println("Hashtable does not contain 1 as value");
}
if( hashtable.containsKey("One") ){
System.out.println("Hashtable contains One as key");
}else{
System.out.println("Hashtable does not contain One as value");
}
Integer one = (Integer) hashtable.get("One");
System.out.println("Value mapped with key \"One\" is " + one);
/*
IMPORTANT: get method returns Object, so we need to downcast it.
*/

System.out.println("Retriving all keys from the Hashtable");
Enumeration e = hashtable.keys();
while( e. hasMoreElements() ){
System.out.println( e.nextElement() );
}
//iterating over values
System.out.println("Retriving all values from the Hashtable");
e = hashtable.elements();
while( e. hasMoreElements() ){
System.out.println( e.nextElement() );
}
//removing the element
System.out.println( hashtable.remove("One") + " is removed from the Hashtable.");
}
}