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
  • hmIterator.next() 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.

Output:

Three
Two
One

Java HashMap program example 2

program output:

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

Recommended Posts:


Editorial Staff

Editorial Staff at FreeWebMentor is a team of professional developers leads by Prem Tiwari

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Solved Programs