Retrieve Set of All Keys in HashMap in Java



First, create a HashMap and add elements

HashMap hm = new HashMap();
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
hm.put("Backpack", new Integer(1200));

Now, retrieve all the keys

Set keys = hm.keySet();
System.out.println("\nKeys...");
Iterator i = keys.iterator();
while (i.hasNext()) {
   System.out.println(i.next());
}

The following is an example to get the set of all key in HashMap

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create hash map
      HashMap hm = new HashMap();
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      hm.put("Backpack", new Integer(1200));
      System.out.println("Map = "+hm);
      Set keys = hm.keySet();
      System.out.println("\nKeys...");
      Iterator i = keys.iterator();
      while (i.hasNext()) {
         System.out.println(i.next());
      }
   }
}

The following is the output

Map = {Backpack=1200, Belt=600, Wallet=700}
Keys...
Backpack
Belt
Wallet
Updated on: 2019-07-30T22:30:24+05:30

272 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements