Subscribe To MegiSoft RSS Feeds!     Your Browser OR  Google Feedburner

Java HashMap

HashMap is one of the classes of the Java standard library. It is a subclass of the class AbstractMap and implements the interfaces Map<K,V>, Serializable, Cloneable. From the diagram, you see that HashMap implements the Map interface, which provides all of the optional map operations. It allows null values and the null key.

HashMap class is similar to Hashtable, except that it is unsynchronized and permits nulls.

The following UML diagram shows the position of the class HashMap in the hierarchy.

Articles: ArrayList  HashSet  TreeSet  HashMap  TreeMap 
Quizzes: Java Collection Quizzes 

hashmap-hierarchy

What is a HashMap in Java?

A HashMap is a data structure that allows you to collect elements. It is one of the classes in the Java library, which contains different methods to add, remove elements and more. Each element of a HashMap has a key and a vlaue.  To use it in your own classes, you need to import the package “java.util” from the Java library  as shown below.

java.util.HashMap<K,V>;

 

Is HashMap my best Java collection class choice?

To answer the question whether HashMap is your best choice, you need to know more details about it it as well as about other Java collection classes. The information and the exercises below will help you to make that decision.

  1. HashMap implements Map interface.
  2. You can add elements to a HashMap based on a Key and a Value by using the method put(key, value).
  3. HashMap allows null values and the null key.
  4. It is not synchronized.
  5. HashMap permits unique key.

 

Exercise 1A: How to create a Java HashMap and add elements to it?

  • Create a HashMap “hmCountry” and add the following countries and country code to it:

“ES”,”Spain”,  “DE”,”Germany”, “FR”,”France”, “CN”,”China”, “US”,”United States”,

“RU”,”Russia”, “GB”,”United Kingdom “, “IN”,”India”, “BR”,”Brazil”, “SA”,”South Africa”.

 

Exercise 1B: How to find the size of a Java HashMap?

  • Print the size of the HashMap to the standard output before and after adding the countries.

Answer 1

  • a. The following code adds the mentioned countries to the HashMap hmCountry.
  • b. The program writes the following to the standard output when it is compiled and run.

HashMap size before adding countries: 0
HashMap size after adding countries: 10

import java.util.HashMap;

public class TestHashMap {

	public static void main(String args[]){

		HashMap<String,String> hmCountry = new HashMap<String,String>();
		System.out.println("HashMap size before adding countries: " + hmCountry.size());

		// adding elements to the HashMap
		hmCountry.put("ES","Spain");
		hmCountry.put("DE","Germany");
		hmCountry.put("FR","France");
		hmCountry.put("CN","China");
		hmCountry.put("US","United States");
		hmCountry.put("RU","Russia");
		hmCountry.put("GB","United Kingdom ");
		hmCountry.put("IN","India");
		hmCountry.put("BR","Brazil");
		hmCountry.put("SA","South Africa");
		System.out.println("HashMap size after adding countries: " + hmCountry.size());
	}
}

Please, leave your questions, feedback and suggestions in the comments below! If you need more explanation by any of the answers, just let me know to update it for you!

Exercise 2: How to retrieve the elements of a Java HashMap and print them to the standard output?

  • Add a piece of code to the exercise 1 to retrieve and print all the countries and their code to the standard output.

Answer 2

  • When the program is compiled and run, it writes the following countries and their code to the standard output.

key: FR, Value: France
key: US, Value: United States
key: RU, Value: Russia
key: BR, Value: Brazil
key: IN, Value: India
key: ES, Value: Spain
key: GB, Value: United Kingdom
key: DE, Value: Germany
key: CN, Value: China
key: SA, Value: South Africa

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class TestHashMap {

	public static void main(String args[]){

		HashMap<String,String> hmCountry = new HashMap<String,String>();
		// adding elements to the HashMap
		hmCountry.put("ES","Spain");
		hmCountry.put("DE","Germany");
		hmCountry.put("FR","France");
		hmCountry.put("CN","China");
		hmCountry.put("US","United States");
		hmCountry.put("RU","Russia");
		hmCountry.put("GB","United Kingdom ");
		hmCountry.put("IN","India");
		hmCountry.put("BR","Brazil");
		hmCountry.put("SA","South Africa");

		// display the HashMap content using Iterator
		Set set = hmCountry.entrySet();
		Iterator iterator = set.iterator();
		while(iterator.hasNext()) {
			Map.Entry ent = (Map.Entry) iterator.next();
			System.out.print("key: " + ent.getKey() + ", Value: ");
			System.out.println(ent.getValue());
		}
	}
}

Please, leave your questions, feedback and suggestions in the comments below! If you need more explanation by any of the answers, just let me know to update it for you!

Exercise 3: How to retrieve and remove an element from a Java HashMap based on its key?

  1. Retrieve the country which has “CN” as a HashMap key.
  2. Remove the country “United Kingdom” from the HashMap hmCountry based on its key “GB“.

Answer 3

  1. When the program is compiled and run, it writes China to the standard output.
  2. The hmCountry doesn’t contain United Kingdom any more.

The key CN belongs to: China
key: FR, Value: France
key: US, Value: United States
key: RU, Value: Russia
key: BR, Value: Brazil
key: IN, Value: India
key: ES, Value: Spain
key: DE, Value: Germany
key: CN, Value: China
key: SA, Value: South Africa

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class TestHashMap {

	public static void main(String args[]){

		HashMap<String,String> hmCountry = new HashMap<String,String>();
		// adding elements to the HashMap
		hmCountry.put("ES","Spain");
		hmCountry.put("DE","Germany");
		hmCountry.put("FR","France");
		hmCountry.put("CN","China");
		hmCountry.put("US","United States");
		hmCountry.put("RU","Russia");
		hmCountry.put("GB","United Kingdom ");
		hmCountry.put("IN","India");
		hmCountry.put("BR","Brazil");
		hmCountry.put("SA","South Africa");

		// retrieve values based on key.
		String country = hmCountry.get("CN");
		System.out.println("The key CN belongs to: " + country);

		// remove values based on key, remove United Kingdom from the HashMap
		hmCountry.remove("GB");

		// display the HashMap content using Iterator
		Set set = hmCountry.entrySet();
		Iterator iterator = set.iterator();
		while(iterator.hasNext()) {
			Map.Entry ent = (Map.Entry) iterator.next();
			System.out.print("key: " + ent.getKey() + ", Value: ");
			System.out.println(ent.getValue());
		}
	}
}

Please, leave your questions, feedback and suggestions in the comments below! If you need more explanation by any of the answers, just let me know to update it for you!

Articles: ArrayList  HashSet  TreeSet  HashMap  TreeMap 
Quizzes: Java Collection Quizzes 
Megisoft.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes. The author of Megisoft is Sar Maroof who has more than a decade of experience with web development mainly with Java, MySql, HTML and more..

Suggested Articles:


Click Here For Info about: Sar Maroof's New Java Book
Author: Sar Maroof
More than a decade of experience with developing web applications mainly with Java.
Sun Certified JSP as well as EJB
CIW Certified Internet Webmaster - Mind IT
Applied Science in Physics HBO Amsterdam
Bachellor Science in Physics at Basra university.
 Subscribe To Megisoft RSS Feeds! (Your Browser)
 Mail This Page To A Friend!
 Bookmark This Page!
Share on FacebookTweet about this on TwitterShare on RedditShare on LinkedIn

Leave a Reply

megisoft © 2016