Iterate value through Java HashMap

Iterate through the values of Java HashMap example. This Java Example shows how to iterate through the values contained in the HashMap object.

In this tutorial, we are sharing an example of Iterate value through Java HashMap.

Following are the ways of traversing through a HashMap in Java programming language.

  • hm.entrySet() is used to retrieve all the key-value pairs called Map.Entries and stores internally into a set.
  • hm.entrySet().iterator() returns a iterator which acts as a cursor and points at the first element of the set and moves on till the end.
  • hmIterator.hasNext() checks for the next element in the set and returns a boolean
  • returns the next element(Map.Entry) from the set.
  • mapElement.getKey() returns the key of the associated Map.Entry
  • mapElement.getValue() return the value of the associated Map.Entry

Java HashMap program example

Copy the below program and execute to see the program output.



Java HashMap program example 2

program output:

{USA=Washington DC, Norway=Oslo, England=London, Germany=Berlin}

If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.

Recommended Posts: