Iterate through the values of HashMap in Java


Use Iterator to iterate through the values of HashMap −

HashMap hm = new HashMap();
// Put elements to the map
hm.put("Bag", new Integer(1100));
hm.put("Sunglasses", new Integer(2000));
hm.put("Frames", new Integer(800));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));

Now, use Iterator to display each and every value and key −

// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
   Map.Entry me = (Map.Entry)i.next();
   System.out.print(me.getKey() + ": ");
   System.out.println(me.getValue());
}

The following is an example to iterate through the values of HashMap −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();
      // Put elements to the map
      hm.put("Bag", new Integer(1100));
      hm.put("Sunglasses", new Integer(2000));
      hm.put("Frames", new Integer(800));
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      Set set = hm.entrySet();
      System.out.println("Elements in HashMap...");
      // Get an iterator
      Iterator i = set.iterator();
      // Display elements
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      System.out.println();
   }
}

Output

Elements in HashMap...
Frames: 800
Belt: 600
Wallet: 700
Bag: 1100
Sunglasses: 2000

Updated on: 30-Jul-2019

345 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements