Java LinkedHashMap clear() Method
The clear() method in Java is a built-in method of the java.util.LinkedHashMap class. This method is used to remove all the key-value mappings from a LinkedHashMap. After invoking this method, the map becomes empty.
This method is very helpful when we want to reuse an existing map object without creating a new one.
Syntax of clear() Method
public void clear()
- Parameters: This method does not accept any parameters.
- Return Value: This method does not return any value i.e., its return type is void.
Examples of Java LinkedHashMap clear() Method
Example 1: In this example, we are going to create a LinkedHashMap with integer keys and string values, then we will use the clear() method to remove all entries.
// Java program to demonstrate
// clear() on LinkedHashMap with Integer keys
import java.util.LinkedHashMap;
public class Geeks {
public static void main(String[] args) {
// Create a LinkedHashMap with Integer keys
LinkedHashMap<Integer, String> m = new LinkedHashMap<>();
// Add entries to the map
m.put(10, "Geeks");
m.put(15, "4");
m.put(20, "Geeks");
m.put(25, "Welcomes");
m.put(30, "You");
System.out.println("Initial Mappings are: " + m);
// Clear all entries from the map
m.clear();
System.out.println("After clear(): " + m);
}
}
Output
Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You} After clear(): {}
Explanation: Here, all entries were removed from the LinkedHashMap using clear() method.
Example 2: In this example, we will map the Integer values to string keys using the clear() method. It also shows how duplicate keys behave.
// Java program to demonstrate
// clear() on LinkedHashMap with String keys
import java.util.LinkedHashMap;
public class Geeks {
public static void main(String[] args) {
// Create a LinkedHashMap with String keys
LinkedHashMap<String, Integer> m = new LinkedHashMap<>();
// Add entries to the map
m.put("Geeks", 10);
m.put("4", 15);
// Overwrites previous key
m.put("Geeks", 20);
m.put("Welcomes", 25);
m.put("You", 30);
System.out.println("Initial Mappings are: " + m);
// Clear all entries from the map
m.clear();
System.out.println("After clear(): " + m);
}
}
Output
Initial Mappings are: {Geeks=20, 4=15, Welcomes=25, You=30} After clear(): {}
Explanation: Here, the duplicate key "Geeks" was updated before clearing. And after calling the clear() method, all entries were removed and the map became an empty map.
Important Points:
- The clear() method deletes all mappings from the LinkedHashMap.
- It does not delete the map object itself, it only deletes its contents.
- It is a void method and does not throw any exceptions.
- This method is very useful for resetting the map state without creating a new instance.