/**
* @author lautturi.com
* Java example: remove element from hashmap in java
*/
import java.util.*;
public class Lautturi {
public static void main(String[] args) {
// Creating a HashMap
HashMap<Integer, String> map = new HashMap<Integer, String>();
// Put elements in Map
map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Cherry");
map.put(4, "Orange");
map.put(5, "Lautturi");
// print the hashmap using for-each loop
for (Map.Entry m : map.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
// remove element associated with key 2
String value = map.remove(2);
System.out.println("Removed value: " + value);
for (Map.Entry m : map.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
}
}
output:
1 Apple 2 Banana 3 Cherry 4 Orange 5 Lautturi Removed value: Banana 1 Apple 3 Cherry 4 Orange 5 Lautturi