0% found this document useful (0 votes)
8 views

HashMap in Java

The document provides a Java program demonstrating the use of HashMap, including creation, insertion, searching, iteration, and removal of key-value pairs. It shows how to add entries, check for the existence of keys, retrieve values, and iterate through the map. The program also includes examples of updating values and removing entries from the HashMap.

Uploaded by

Roshan K
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

HashMap in Java

The document provides a Java program demonstrating the use of HashMap, including creation, insertion, searching, iteration, and removal of key-value pairs. It shows how to add entries, check for the existence of keys, retrieve values, and iterate through the map. The program also includes examples of updating values and removing entries from the HashMap.

Uploaded by

Roshan K
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

HashMap in Java

import java.util.*;

public class Hashing {


public static void main(String args[]) {
//Creation
HashMap<String, Integer> map = new HashMap<>();

//Insertion
map.put("India", 120);
map.put("US", 30);
map.put("China", 150);

System.out.println(map);

map.put("China", 180);
System.out.println(map);

//Searching
if(map.containsKey("Indonesia")) {
System.out.println("key is present in the map");
} else {
System.out.println("key is not present in the map");
}

System.out.println(map.get("China")); //key exists


System.out.println(map.get("Indonesia")); //key doesn't exist

//Iteration (1)
for( Map.Entry<String, Integer> e : map.entrySet()) {
System.out.println(e.getKey());
System.out.println(e.getValue());
}

//Iteration (2)
Set<String> keys = map.keySet();
for(String key : keys) {
System.out.println(key+ " " + map.get(key));
}
//Removing
map.remove("China");
System.out.println(map);

}
}

You might also like