- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to retrieve the set of all keys and values in HashMap
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
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("
Keys..."); Set keys = hm.keySet(); Iterator i = keys.iterator(); while (i.hasNext()) { System.out.println(i.next()); } System.out.println("
Values..."); 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
- Related Articles
- Java Program to retrieve the set of all keys in HashMap
- Java Program to retrieve the set of all values in HashMap
- Retrieve all the keys from HashMap in Java
- Retrieve a set of Map.Entry elements from a HashMap in Java
- Remove all values from HashMap in Java
- How to retrieve windows registry keys and values using PowerShell?
- Sorting a HashMap according to keys in Java
- Java Program to find keys from a Linked HashMap and store it in a list
- Sort HashMap based on keys in Java
- Java Program to find keys from both the Linked HashMap and store it in a list alternatively
- Iterate through the values of HashMap in Java
- Python program to print the keys and values of the tuple
- Java Program to replace key and value in HashMap with identical key and different values
- Set Date value in Java HashMap?
- Extract values from HashMap in Java

Advertisements