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.
Copy the below program and execute to see the program output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.Collection; import java.util.HashMap; import java.util.Iterator; public class IterateValuesOfHashMapExample { public static void main(String[] args) { //create HashMap object HashMap hMap = new HashMap(); //add key value pairs to HashMap hMap.put("1","One"); hMap.put("2","Two"); hMap.put("3","Three"); //get Collection of values contained in HashMap using Collection //values() method of HashMap class Collection c = hMap.values(); //obtain an Iterator for Collection Iterator itr = c.iterator(); //iterate through HashMap values iterator while(itr.hasNext()) System.out.println(itr.next()); } } |
Output:
Three
Two
One
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Import the HashMap class import java.util.HashMap; public class MyClass { public static void main(String[] args) { // Create a HashMap object called capitalCities HashMap<String, String> capitalCities = new HashMap<String, String>(); // Add keys and values (Country, City) capitalCities.put("England", "London"); capitalCities.put("Germany", "Berlin"); capitalCities.put("Norway", "Oslo"); capitalCities.put("USA", "Washington DC"); System.out.println(capitalCities); } } |
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.