HashMap is an object that stores both “key/value” as a pairs. In this article, we show you how to create a HashMap instance and iterates the HashMap data.

["mkyong","1000.00"] = ["key","value"]

In above, “mkyong” is the key , “1000.00″ is the value. By given a key “mkyong”, you can get the value “1000.00″.

Example

See full example of using HashMap.

package com.mkyong.core;
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
 
public class Number {
	public static void main(String[] args) {
		try {
 
			Map mMap = new HashMap();
			mMap.put("PostgreSQL", "Free Open Source Enterprise Database");
			mMap.put("DB2", "Enterprise Database , It's expensive");
			mMap.put("Oracle", "Enterprise Database , It's expensive");
			mMap.put("MySQL", "Free Open SourceDatabase");
 
			Iterator iter = mMap.entrySet().iterator();
 
			while (iter.hasNext()) {
				Map.Entry mEntry = (Map.Entry) iter.next();
				System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
			}
 
			mMap.put("Oracle", "Enterprise Database , It's free now ! (hope)");
 
			System.out.println("One day Oracle.. : " + mMap.get("Oracle"));
 
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}
}

Output

PostgreSQL : Free Open Source Enterprise Database
MySQL : Free Open SourceDatabase
Oracle : Enterprise Database , It's expensive
DB2 : Enterprise Database , It's expensive
One day Oracle.. : Enterprise Database , It's free now ! (hope)
Tags :
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider making a donation to the charity, thanks.

Related Posts

Popular Posts