HashMap Example in Java

import java.util.HashMap;
import java.util.Set;

public class HashMapExample {
	public static void main(String[] args) {
		// Creating a HashMap key is Integer type and value is String type
		HashMap<Integer, String> myHashMap = new HashMap<Integer, String>();
		
		//adding key-value pair to HashMap
		myHashMap.put(1, "Element1");
		myHashMap.put(2, "Element2");
		myHashMap.put(3, "Element3");
		myHashMap.put(4, "Element4");

		// Printing the elements it contains
		System.out.println(myHashMap);

		// Iterating each elements of myHashMap 
		//Get the set view of the keys contained in this map
		Set<Integer> keys = myHashMap.keySet();
		for(Integer key :keys){
			myHashMap.get(key);
		}

		// containsKey method check whether the map contains the specified key or not
		// containsValue method check whether the map contains the specified value or not
		System.out.println(myHashMap.containsKey(1)); // true
		System.out.println(myHashMap.containsValue("Element1"));// true

		// Print the size of the map
		System.out.println("size: " + myHashMap.size());

		// Removes an mapping for the specified key from the map if present
		myHashMap.remove(1);

		System.out.println("After removing Element1 : " + myHashMap);

		// Removes all of the elements from this map
		myHashMap.clear();
		System.out.println("After calling clear() : " + myHashMap);

		// isEmpty() Returns true if the map contains no elements.
		System.out.println("is empty :" + myHashMap.isEmpty());
	}
}












Related Examples


Write a program to get list of all the files from a given directory?
Write a Comparator to compare students based upon their name and age?
Simple Array Sorting Program.
Bubble Sort Example.
Write a java program to check if a number is Armstrong number or not?








Receive Latest Java Examples in Your Email: