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

HashMap in Java

This document discusses how to use a HashMap in Java. It shows how to create a HashMap, insert key-value pairs, search for keys, iterate through the map, and remove entries. Specifically, it creates a HashMap of countries to populations, inserts several entries, searches for keys, iterates through the map in two ways, and removes one entry.

Uploaded by

Naresh todkar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

HashMap in Java

This document discusses how to use a HashMap in Java. It shows how to create a HashMap, insert key-value pairs, search for keys, iterate through the map, and remove entries. Specifically, it creates a HashMap of countries to populations, inserts several entries, searches for keys, iterates through the map in two ways, and removes one entry.

Uploaded by

Naresh todkar
Copyright
© © All Rights Reserved
Available Formats
Download as 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