HashMap in Java
HashMap
HashMap stores data in key-value pairs. If you want to store values like {address=USA, fathername=Himal Sharma}. You can store data in a hash map. You must import java.util.HashMap;
Syntax
import java.util.HashMap; // First Import this
HashMap<String, String> personalDetails = new HashMap<String, String>();
For String Key And Double Value
HashMap<String, Double> hashMapName = new HashMap<String, Double>();
For Int Key And String Value
HashMap<Integer, String> hashMapName = new HashMap<Integer, String>();
Example
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// Create a HashMap object i.e personalDetails
HashMap<String, String> personalDetails = new HashMap<String, String>();
// Adding Keys and Values.
personalDetails.put("name", "Milan Sharma");
personalDetails.put("address", "USA");
personalDetails.put("fathername", "Himal Sharma");
personalDetails.put("mothername", "Sita Sharma");
System.out.println(personalDetails);
}
}
Some Useful Methods For HashMap
Here personalDetails is HashMap variable. You can create a variable with any name. You can create of any type.
Methods | Description |
---|---|
personalDetails.get(“name”); | To Access item. prints Milan Sharma |
personalDetails.remove(“name”); | Removes item. remove Milan Sharma and USA |
personalDetails.clear(); | Clear all items |
personalDetails.size(); | Get size of HashMap |
Loop Through HashMap / Print All Keys
// Print all keys
for (String i : personalDetails.keySet()) {
System.out.println(i);
}
To Print All Values
// Print all values
for (String i : personalDetails.values()) {
System.out.println(i);
}
To Print Keys And Values
// Print keys and values
for (String i : personalDetails.keySet()) {
System.out.println("key is: " + i + " value is: " + personalDetails.get(i));
}
Example: Java Program To Store Name and Salary
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// Create a HashMap object i.e salaries
HashMap<String, Double> salaries = new HashMap<String, Double>();
// Adding name and salary.
salaries.put("Ram Sharma", 1100.0);
salaries.put("Hari Sharma",1200.0 );
salaries.put("Rocky Yadav", 2550.0);
salaries.put("Menuka Pradhan", 1500.0);
for (String name : salaries.keySet()) {
System.out.println( name + " salary is : " + salaries.get(name));
}
}
}