Iterate over HashMap to get Key and Value in Java , Add records to HashMap

Sharing is Caring

Iterating over other collection is easy as compare to iterate over HashMap is not same as other collections, It’s a bit tricky than normal iteration 😉
See in this code –
How to add values to HashMap?
and How to iterate over HashMap to get Key and Values?

package client;

import java.util.HashMap;
import java.util.Iterator;

public class IterateHashMap {
public IterateHashMap() {

public static void main(String[] args) {
HashMap<Integer, String> mapVal = new HashMap<Integer, String>();

//Add values to Map
mapVal.put(1, "value 1");
mapVal.put(2, "value 2");
mapVal.put(3, "value 3");
mapVal.put(4, "value 4");

//Create Iterator from keySet
Iterator iter = mapVal.keySet().iterator();
//Iterate over hashmap to get key
while (iter.hasNext()) {
int key = (Integer);
//Use this key to find value
String value = mapVal.get(key).toString();
System.out.println("**KEY** " + key + " AND VALUE** " + value);


Cheers 🙂 Happy Learning

Related Posts

Leave a Reply

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