How to iterate a HashMap in Java

There are several ways to iterate a HashMap in Java. However, the three listed below are the most common.


Three ways to iterate a Hashmap

  1. Using a for loop to iterate through a HashMap
  2. Using a forEach to iterate through a HashMap
  3. Using an iterator to iterate through a HashMap
svg viewer

1. Using a for loop to iterate through a HashMap

In the code below, hash_map.entrySet() is used to return a set view of the mapped elements. Now, getValue() and getKey() functions, key-value pairs can be iterated.

// importing library.
import java.util.HashMap;
import java.util.Map;
// class for iterating HashMap.
public class Iterate {
public static void main(String[] arguments) {
// creating HashMap.
Map<Integer, String> hash_map = new HashMap<Integer, String>();
// inserting sets.
hash_map.put(1, "Thor");
hash_map.put(2, "Iron man");
// iterating using for loop.
for (Map.Entry<Integer, String> set : hash_map.entrySet()) {
System.out.println(set.getKey() + " = " + set.getValue());
}
}
}

2. Using a forEach to iterate through a HashMap

In the code below, the forEach function is used to iterate the key-value pairs.

// importing libraries.
import java.util.HashMap;
import java.util.Map;
// class for iterating HashMap.
public class Iterate{
public static void main(String[] arguments) {
// creating hash_map.
Map<Integer, String> hash_map = new HashMap<Integer, String>();
// inserting sets in the hash_map.
hash_map.put(1, "Thor");
hash_map.put(2, "Iron man");
// iterating it using forEach.
hash_map.forEach((key,value) -> System.out.println(key + " = " + value));
}
}

3. Using an iterator to iterate through a HashMap

In the code below, an iterator is used to iterate the each mapped pair.

// importing java libraries.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
// class for iterating HashMaps.
public class Iterate {
public static void main(String[] arguments) {
// creating hash_map.
Map<Integer, String> hash_map = new HashMap<Integer, String>();
// inserting value.
hash_map.put(1, "Thor");
hash_map.put(2, "Iron man");
// setting up iterator.
Iterator<Entry<Integer, String>> it = hash_map.entrySet().iterator();
// iterating every set of entry in the HashMap.
while (it.hasNext()) {
Map.Entry<Integer, String> set = (Map.Entry<Integer, String>) it.next();
System.out.println(set.getKey() + " = " + set.getValue());
}
}
}
Copyright ©2024 Educative, Inc. All rights reserved