- 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 create a HashMap and add key-value pairs
To create a HashMap, use the HashMap class −
HashMap hm = new HashMap();
Add elements to the HashMap in the form of key-value pair −
hm.put("Bag", new Integer(1100)); hm.put("Wallet", new Integer(700)); hm.put("Belt", new Integer(600));
The following is an example to create HashMap and add key-value pair −
Example
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("Wallet", new Integer(700)); hm.put("Belt", new Integer(600)); // Get a set of the entries Set set = hm.entrySet(); // 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
Belt: 600 Wallet: 700 Bag: 1100
- Related Articles
- Create a TreeMap in Java and add key-value pairs
- Java Program to remove key value pair from HashMap?
- Java Program to Update value of HashMap using key
- Java Program to replace key and value in HashMap with identical key and different values
- Java Program to Get key from HashMap using the value
- Java Program to remove a key from a HashMap
- How to add key/value pairs in SortedList in C#?
- How to use null value as key in Java HashMap
- Python Program to print key value pairs in a dictionary
- JavaScript: How to Create an Object from Key-Value Pairs
- Get the value associated with a given key in Java HashMap
- Modify the value associated with a given key in Java HashMap
- Java Program to remove a key from a HashMap only if it is associated with a given value
- Java Program to copy all the key-value pairs from one Map into another
- Python Program to Alternate list elements as key-value pairs

Advertisements