HashMap In Java

In today’s discussion, we will cover Java HashMap with examples, which is intended to meet the learning needs of our learners

Java HashMap

You learned in the ArrayList chapter that arrays contain items in an ordered collection that can be accessed by index numbers (ints).

As far as Java HashMaps are concerned, Hashmap stores the items in groups of “key/value” pairs, and you can access them by an index datatype rather than using int only (e.g. String).

The key (index) of one object is used to access the value of another object.

There are two types of data it can store: String keys and Character values, or the same type, like String keys and String values.

Make a HashMap object and name it sports_players for storing String keys and String values:

import java.util.HashMap; // HashMap class is imported here
HashMap<String, String> sports_players = new HashMap<String, String>();

Make a HashMap object and name it rank_Id for storing String keys and String values:

import java.util.HashMap; // HashMap class is imported here
  HashMap<Integer, Integer> rank_Id = new HashMap<Integer, Integer>();


Java HashMap Put()

There are many useful methods in the HashMap class. You can use the put() method to add items to it, for example:

Declare a HashMap object and name it sports_players for storing String keys as sports name and String values as famous player name.

Example: 

import java.util.HashMap; // HashMap class is imported herepublic class Main { public static void main(String[] args) { HashMap<String, String> sports_players = new HashMap<String, String>(); // The object of Hashmap is created heere in which key and value both are of type String.sports_players.put("Football","Cristiano Ronaldo"); sports_players.put("Cricket","Sachin Tendulkar"); sports_players.put("Hockey","Wayne Gretzky"); sports_players.put("Baseball","Babe Ruth"); sports_players.put("Rugby","Jonah Lomu");System.out.println(sports_players);} }

Similarly, we have initialize a HashTree object that stores rank as keys and Id as value:

Example: 

import java.util.HashMap; // HashMap class is imported here public class Main { public static void main(String[] args) { HashMap<Integer, Integer> rank_Id = new HashMap<Integer, Integer>();// Here, a HashMap object is created and named as rank_Id, whose key and value are both integers. rank_Id.put(1,10001); rank_Id.put(2,10002); rank_Id.put(3,10003); rank_Id.put(4,10004); rank_Id.put(5,10005); System.out.println(rank_Id); } }

 


Java HashMap Get()

When we discuss Java HashMap, the get() method and the key are used to access values in a HashMap.

Example: 

import java.util.HashMap; // HashMap class is imported herepublic class Main { public static void main(String[] args) {HashMap<String, String> it_Firms = new HashMap<String,String >();it_Firms.put("1","Cognizant"); it_Firms.put("2","Vates-Software"); it_Firms.put("3","MantorMate"); it_Firms.put("4","Resultant"); it_Firms.put("5","Fortegrp"); // All Elements of HashMapSystem.out.println(it_Firms);// By accessing the value at key number 3System.out.println("\nValue at key 3: "+it_Firms.get("3")); } }

Another Approach:

Example: 

import java.util.HashMap; // HashMap class is imported herepublic class Main { public static void main(String[] args) {HashMap<Integer,Integer> rank_Age = new HashMap<Integer,Integer>();rank_Age.put(1,21); rank_Age.put(2,25); rank_Age.put(3,31); rank_Age.put(4,41); rank_Age.put(5,37);// All Elements of HashMapSystem.out.println(rank_Age);// By accessing the Age at key number 2System.out.println("\nValue at key 2: "+rank_Age.get(2));} }

 


Java HashMap Remove()

Using the remove() method, remove an item by referencing its key.

The example below shows the removal of Key (“Team 4”) valued as Cleveland Cavailers.

Hashmap remove Example: 1 

import java.util.HashMap; // HashMap class is imported herepublic class Main { public static void main(String[] args) {HashMap<String,String> nba_Teams = new HashMap<String,String>();nba_Teams.put("Team 1"," Boston Celtics"); nba_Teams.put("Team 2"," Chicago Bulls"); nba_Teams.put("Team 3"," Atlanta Hawks"); nba_Teams.put("Team 4"," Cleveland Cavaliers"); nba_Teams.put("Team 5"," Detroit Pistons");// Here we print all Elements of the HashMap Object named as nba_Teams before removing an itemSystem.out.println("\nBefore Removing Value: "+nba_Teams);// Removing Cleveland Cavaliers by using its key (Team 4)String removed= nba_Teams.remove("Team 4");System.out.println("\nRemoved Value is: "+removed);// Printing all elements of HashMap after an element was removed:System.out.println("\nAfter Removing value: "+nba_Teams);} }

Example: 2 

import java.util.HashMap; // HashMap class is imported herepublic class Main { public static void main(String[] args) {HashMap<Float,Float> person_Id_Height = new HashMap<Float,Float>();person_Id_Height.put(10f,5.4f); person_Id_Height.put(20f,5.6f); person_Id_Height.put(30f,5.7f); person_Id_Height.put(40f,6.2f); person_Id_Height.put(50f,5.11f);// Here we print all Elements of the HashMap Object named as person_Id_Height before the item is elementSystem.out.println("\nBefore Removing Value: "+person_Id_Height);// Removing from person_Id_Height HashMap by using its key (40f)float removed= person_Id_Height.remove(40f);System.out.println("\nRemoved Value is: "+removed);// Printing all elements of HashMap after an element was removed:System.out.println("\nAfter Removing value: "+person_Id_Height);} }

 

Using the clear() method, you can remove all items of the HashMap Object:

Example: 

import java.util.HashMap; // HashMap class is imported herepublic class Main { public static void main(String[] args) {HashMap<String,String> product_code = new HashMap<String,String>();product_code.put("Cookies","102313"); product_code.put("Biscuits","153532"); product_code.put("Snacks","632123"); product_code.put("PopCorns","361232"); product_code.put("Chocolates","734231");// Here we print all Elements of the HashMap Object named as product_codeSystem.out.println("HashMap: "+product_code);// After using .clear() method our HashMap becomes emptyproduct_code.clear();// Printing all elements of HashMap after all elements were removed:System.out.println("After clearing the HashMap we get: "+product_code);} }

Here we clear the entire HashMap using the clear() method:

Example: 

import java.util.HashMap; // HashMap class is imported herepublic class Main { public static void main(String[] args) {HashMap<Float,Float> results_division_ = new HashMap<Float,Float>();results_division_.put(14f/5f,2.8f); results_division_.put(18f/7f,2.57f); results_division_.put(19f/4f,4.75f); results_division_.put(11f/3f,3.66f);// Here we print all Elements of the HashMap Object named as results_division_System.out.println("HashMap: "+results_division_);// After using .clear() method our HashMap becomes emptyresults_division_.clear();// Printing all elements of HashMap after all elements were removed:System.out.println("After clearing the HashMap we get: "+results_division_);} }

HashMap Size

The size() method can be used to find out how many items there are in the HashMap:

Example: 

import java.util.HashMap; // HashMap class is imported herepublic class Main { public static void main(String[] args) {HashMap<String,String> rank_billionaires_name = new HashMap<String,String>();rank_billionaires_name.put("Rank 1: "," Bernard Arnault & family"); rank_billionaires_name.put("Rank 2: "," Elon Musk"); rank_billionaires_name.put("Rank 3: "," Gautam Adani"); rank_billionaires_name.put("Rank 4: "," Jeff Bezos");// Here we print all Elements of the HashMap Object named as rank_billionaires_nameSystem.out.println("HashMap: "+rank_billionaires_name);// By using size() method we can determine the size of our HashMapSystem.out.println("\nSize of HashMap: "+rank_billionaires_name.size()); } }

Example: 

import java.util.HashMap; // HashMap class is imported herepublic class Main { public static void main(String[] args) {HashMap<Character,Character> vowels_List = new HashMap<Character,Character>();vowels_List.put('a','A'); vowels_List.put('e','E'); vowels_List.put('i','I'); vowels_List.put('o','O'); vowels_List.put('u','U'); // Here we print all Elements of the HashMap Object named as vowels_ListSystem.out.println("Vowels HashMap: "+vowels_List);// By using size() method we can determine the size of our HashMapSystem.out.println("\nSize of HashMap: "+vowels_List.size()); } }

Loop Through a HashMap

A for-each loop traverses a HashMap’s items.

Remember: If you only want the keys, use the keySet() method, and if you only want the values, use the values() method.

The following examples show how can we print all the keys of the HashMap using the keySet() method:

Example: 1 

import java.util.HashMap; // HashMap class is imported herepublic class Main { public static void main(String[] args) {HashMap<String, String> it_Firms = new HashMap<String,String >();it_Firms.put("1","Cognizant"); it_Firms.put("2","Vates-Software"); it_Firms.put("3","MantorMate"); it_Firms.put("4","Resultant"); it_Firms.put("5","Fortegrp");// Using for-each loop to traverse through the keys of HashMap object named it_Firmsfor(String mrx:it_Firms.keySet()){ System.out.println(mrx); } } }

Example:2 

import java.util.HashMap; // HashMap class is imported herepublic class Main { public static void main(String[] args) {HashMap<Integer,Integer> odd_Even = new HashMap<Integer,Integer>();odd_Even.put(1,2); odd_Even.put(3,4); odd_Even.put(5,6); odd_Even.put(7,8); odd_Even.put(9,10);// Using for-each loop to print through the keys of HashMap object named odd_Evenfor(Integer ample:odd_Even.keySet()){ System.out.println(ample); } } }

Similarly, we can also traverse and print the values of the HashMap using the values() method:

Example:3 

import java.util.HashMap; // HashMap class is imported herepublic class Main { public static void main(String[] args) {HashMap<String, String> it_Firms = new HashMap<String,String >();it_Firms.put("1","Cognizant"); it_Firms.put("2","Vates-Software"); it_Firms.put("3","MantorMate"); it_Firms.put("4","Resultant"); it_Firms.put("5","Fortegrp");// Using for-each loop to print the values of HashMap object named it_Firms using the values() methodfor(String ample:it_Firms.values()){ System.out.println(ample); }} }

We have printed the keys and values from the object named as odd_Even of the HashMap:

Example:4 

import java.util.HashMap; // HashMap class is imported herepublic class Main { public static void main(String[] args) {HashMap<Integer,Integer> odd_Even = new HashMap<Integer,Integer>();odd_Even.put(1,2); odd_Even.put(3,4); odd_Even.put(5,6); odd_Even.put(7,8); odd_Even.put(9,10);// Using for-each loop to print all the values of HashMap object named odd_Even using the values() methodfor(Integer ample:odd_Even.values()){ System.out.println(ample); } } }

Likewise, We can also print both (Keys and values) at a time using the keySet() method and get() method:

Example:5 

import java.util.HashMap; // HashMap class is imported herepublic class Main { public static void main(String[] args) {HashMap<String, String> it_Firms = new HashMap<String,String >();it_Firms.put("1","Cognizant"); it_Firms.put("2","Vates-Software"); it_Firms.put("3","MantorMate"); it_Firms.put("4","Resultant"); it_Firms.put("5","Fortegrp");// We can also access the keys and values at a timefor(String ample:it_Firms.keySet()){ System.out.println("Key: "+ample+" Value: "+it_Firms.get(ample));}} }

Example:6 

import java.util.HashMap; // HashMap class is imported herepublic class Main { public static void main(String[] args) {HashMap<Integer,Integer> odd_Even = new HashMap<Integer,Integer>();odd_Even.put(1,2); odd_Even.put(3,4); odd_Even.put(5,6); odd_Even.put(7,8); odd_Even.put(9,10);// As we did in the example above, we can print the keys and the values at a same time using th for-each loopfor(Integer mrx:odd_Even.keySet()){ System.out.println("Key Number: "+mrx+" Value: "+odd_Even.get(mrx)); } } }

 


Other Types

There are actually objects that make up the keys and values of a HashMap. Objects of type “String” and “Integer” were used in the examples above. Strings are objects in Java (not primitive types).

If you’d like to access other types, such as int, you’ll need to specify an equivalent wrapper class: Integer.

When it comes to other primitive types, use Boolean for boolean, character for character, double for double, etc.

To store Integer keys and String values, we create a HashMap object called silent_letter_words:

Example: 

import java.util.HashMap;public class Main { public static void main(String[] args) {HashMap <Integer,String> silent_letter_words=new HashMap<Integer,String>();silent_letter_words.put(1,"Bomb"); silent_letter_words.put(2,"Knife"); silent_letter_words.put(3,"Kitchen"); silent_letter_words.put(4,"Wrap"); silent_letter_words.put(5,"Cupboard");for(int mrx:silent_letter_words.keySet()){ System.out.println("Number "+mrx+" ="+" Word: "+silent_letter_words.get(mrx));}} }

Furthermore, we can also print the name of persons as keys and their body weights as value as shown below:

Example: 

import java.util.HashMap;public class Main { public static void main(String[] args) {HashMap <String,Double> person_Weight=new HashMap<String,Double>();person_Weight.put("Joseph",56.8d); person_Weight.put("Diana",64.2d); person_Weight.put("Emma",44.1d); person_Weight.put("Sophia",77.4d); person_Weight.put("Noah",58.9d);for(String ample:person_Weight.keySet()){ System.out.println(ample+" have "+"Weight= "+person_Weight.get(ample)+" kgs");}} }

 

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *