• September 3, 2014
  • Core Java
  • Comments Off on HashMap in java

HashMap in java

HashMap:

HashMap extends AbstractMap class and implements the Map interface. It contains the elements in key-value pair form. It not maintains any order for its elements. It not allowed duplicate key. A HashMap can have only one null key and multiple null values.

 HashMap example:

HashMapTest.java

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
 
/**
 * This class is used to show the HashMap functionality.
 * @author javawithease
 */
public class HashMapTest {
	public static void main(String args[]){
		//Create HashMap object.
		Map hashMap = new HashMap();
 
		//Add objects to the HashSet.
		hashMap.put(4, "Roxy");
		hashMap.put(2, "Sunil");
		hashMap.put(5, "Sandy");
		hashMap.put(1, "Munish");
		hashMap.put(3, "Pardeep");
 
		//Print the HashMap object.
		System.out.println("HashMap elements:");
		System.out.println(hashMap);
 
		//Get iterator
		Set set=hashMap.entrySet();  
		Iterator iterator=set.iterator();  
 
		//Print the HashMap elements using iterator.
		System.out.println("HashMap elements using iterator:");
		while(iterator.hasNext()){
		   Map.Entry mapEntry=(Map.Entry)iterator.next();  
		   System.out.println("Key: " + mapEntry.getKey() + ", " +
		   		"Value: " + mapEntry.getValue());  
		}  
	}
}

Output:

HashMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy}
HashMap elements using iterator:
Key: 1, Value: Munish
Key: 2, Value: Sunil
Key: 3, Value: Pardeep
Key: 4, Value: Roxy
Key: 5, Value: Sandy

Download this example.
 
Next Topic: LinkedHashMap in java with example.
Previous Topic: LinkedList in java with example.

Related Topics:

Collection framework in java.
Collection interfaces in java.
Collection interface in java with example.
Set interface in java with example.
SortedSet interface in java with example.
List interface in java with example.
Map interface in java with example.
Daemon thread in java in java with example.
SortedMap interface in java with example.
Queue interface in java with example.
Deque interface in java with example.
Enumeration interface in java with example.
Collection classes in java with example.
HashSet in java with example.
LinkedHashSet in java with example.
TreeSet in java with example.
ArrayList in java with example.
LinkedList in java with example.
HashMap in java with example.
LinkedHashMap in java with example.
TreeMap in java with example.
PriorityQueue in java with example.
ArrayDeque in java with example.
Abstract classes in collection framework in java with example.
Sorting in java with example.
Comparable interface in java with example.
Comparator interface in java with example.
Properties class in java with example.
Hashtable in java with example.
ListIterator interface in java with example.

 


Comments are closed.