How to Loop Through a HashMap in Java


In this example, we will learn the method to loop through a HashMap in Java.

Source Code

package com.beginner.examples;

import java.util.HashMap;

public class LoopHashMap {
  public static void main(String[] args) {
    HashMap maps = new HashMap();
    maps.put("A", "a");
    maps.put("B", "b");

    for (String s : maps.keySet()) { // loop through a HashMap
      System.out.println("key: " + s + " , value: " + maps.get(s));
    }
  }
}

Output:

key: A , value: a
key: B , value: b

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments