Remove all entries from java map
Java Map is a data structure that holds key->value pairs. In this article we will see how to delete all entries in the map in java easily and efficetively.
Method clear()
clear() method is method that does not return any thing (void return type) and is part of the Map interface.
Each implementation subclasses provides an implementation. clear () methods deleted all entries and turn them map into empty map.
Clear method
static void clearALLItemsInMap() {
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
map.put(5, "five");
map.put(6, "five");
newline("Original Map");
map.forEach( (a,b) -> {
System.out.println( a + " -> " + b);
});
//clear the map
map.clear();
newline("After classing clear() Map");
map.forEach( (a,b) -> {
System.out.println(a + " -> " + b);
});
}
Output of above program.
Original Map 1 -> one 2 -> two 3 -> three 4 -> four 5 -> five 6 -> five After classing clear() Map empty
Summary
For removing all the entries from java map, clear() method is the best option. Also please note that the clear() method is implemented in each of its implementation classes like, HashMap, TreeMap, LinkedHashMap etc.
No comments :
Post a Comment
Please leave your message queries or suggetions.