Traverse through a HashMap in Java

Java 8Object Oriented ProgrammingProgramming

To traverse through a HashMap, use Iterator. The HashMap class uses a hashtable to implement the Map interface. This allows the execution time of basic operations, such as get( ) and put( ), to remain constant even for large sets.

Following is the code to traverse through a HashMap −


import java.util.*;
public class Main {
   public static void main(String args[]) {
      HashMap hashMap = new HashMap();
      hashMap.put("John", new Integer(10000));
      hashMap.put("Tim", new Integer(25000));
      hashMap.put("Adam", new Integer(15000));
      hashMap.put("Katie", new Integer(30000));
      hashMap.put("Jacob", new Integer(45000));
      hashMap.put("Steve", new Integer(23000));
      hashMap.put("Nathan", new Integer(25000));
      hashMap.put("Amy", new Integer(27000));
      Set set = hashMap.entrySet();
      Iterator iterator = set.iterator();
      while(iterator.hasNext()) {
         Map.Entry map = (Map.Entry);
         System.out.print(map.getKey() + ": ");
      System.out.println("Size of IdentintyHashMap: "+hashMap.size());
      int bonus = ((Integer)hashMap.get("Amy")).intValue();
      hashMap.put("Amy", new Integer(bonus + 5000));
      System.out.println("Amy's salary after bonus = " + hashMap.get("Amy"));
      int deductions = ((Integer)hashMap.get("Steve")).intValue();
      hashMap.put("Steve", new Integer(deductions - 3000));
      System.out.println("Steve's salary after deductions = " + hashMap.get("Steve"));


Adam: 15000
Nathan: 25000
Katie: 30000
Steve: 23000
John: 10000
Tim: 25000
Amy: 27000
Jacob: 45000
Size of IdentintyHashMap: 8
Amy's salary after bonus = 32000
Steve's salary after deductions = 20000

You can also traverse through a HashMap using the for-each loop. The keySet() and values() methods are needed here to display the keys and values respectively. Let us now see another example wherein we will be traversing through a HashMap using for-each −


import java.util.HashMap;
public class Main {
   public static void main(String[] args) {
      HashMap<String, String> students = new HashMap<String, String>();
      students.put("John", "Maths");
      students.put("Tim", "Political Science");
      students.put("Steve", "English");
      students.put("Nathan", "Science");
      for (String s : students.keySet()) {
         System.out.println("key= " + s + ", value= " + students.get(s));


key= Nathan, value= Science
key= Steve, value= English
key= John, value= Maths
key= Tim, value= Political Science
Updated on 20-Sep-2019 11:25:42