In this video, we will write a Java program to traverse through a HashMap in Java.
We have discussed 3 different approaches as follows:
1. Using forEach
2. Using for loop
3. Using Iterator
Using forEach: In this method, we define a a hash map. Then we use the forEach method of hashmap to iterate on the entries. On each iteration we print the key and value pair.
Using for loop: In this method, we iterate on the hashmap and we store each element as a Map.Entry element. Then we get the key and the value of each entry using getKey() and getValue() methods respectively.
Using Iterator: In this method, we get an iterator of the entry set from the hashmap, using entrySet().iterator() method on hashmap variable. Then, we iterate using a while loop, till the iterator is exhausted. In each iteration, we get the value of an Entry using .next() method on the iterator.
Traverse through a hashmap in Java:
https://www.geeksforgeeks.org/traverse-through-a-hashmap-in-java/