CodesJava

Easy learning with example program codes

how to create a 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.

Example

package com.codesjava;
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
 
public class Test {
	public static void main(String args[]){
		//Create HashMap object.
		Map<Integer, String> hashMap = new HashMap<Integer, String>();
 
		//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

Highest salary emp: Name: Mahesh, Salary: 80000
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki