Java Program to retrieve the set of all keys and values in HashMap

Java 8Object Oriented ProgrammingProgramming

To retrieve the set of keys from HashMap, use the keyset() method. However, for set of values, use the values() method.

Create a HashMap −

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

Now, retrieve the keys −

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

Retrieve the values −

Collection getValues = hm.values();
i = getValues.iterator();
while (i.hasNext()) {
   System.out.println(i.next());
}

The following is an example to get the set of all keys and values 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);
      System.out.println("\nKeys...");
      Set keys = hm.keySet();
      Iterator i = keys.iterator();
      while (i.hasNext()) {
         System.out.println(i.next());
      }
      System.out.println("\nValues...");
      Collection getValues = hm.values();
      i = getValues.iterator();
      while (i.hasNext()) {
         System.out.println(i.next());
      }
   }
}

Output

Map = {Backpack=1200, Belt=600, Wallet=700}

Keys...
Backpack
Belt
Wallet

Values...
1200
600
700
raja
Published on 11-Jan-2019 11:57:56
Advertisements