LinkedHashMap clear() Method in Java
Last Updated :
25 Jun, 2018
The java.util.LinkedHashMap.clear() is an inbuilt method of LinkedHashMap class in Java and is used to clear all the elements or the mappings from the denoted LinkedHashMap. The map will become empty after the operation is performed.
Syntax:
Linked_Hash_Map.clear()
Parameters: The method does not take any parameters.
Return Value: The method does not return any value.
Below programs illustrate the java.util.LinkedHashMap.clear() method:
Program 1: Mapping String Values to Integer Keys.
import java.util.*;
public class Linked_Hash_Map_Demo {
public static void main(String[] args)
{
LinkedHashMap<Integer, String> li_hash_map =
new LinkedHashMap<Integer, String>();
li_hash_map.put( 10 , "Geeks" );
li_hash_map.put( 15 , "4" );
li_hash_map.put( 20 , "Geeks" );
li_hash_map.put( 25 , "Welcomes" );
li_hash_map.put( 30 , "You" );
System.out.println( "Initial Mappings are: " + li_hash_map);
li_hash_map.clear();
System.out.println( "Finally the maps look like this: " + li_hash_map);
}
}
|
Output:
Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
Finally the maps look like this: {}
Program 2: Mapping Integer Values to String Keys.
import java.util.*;
public class Linked_Hash_Map_Demo {
public static void main(String[] args)
{
LinkedHashMap<String, Integer> li_hash_map =
new LinkedHashMap<String, Integer>();
li_hash_map.put( "Geeks" , 10 );
li_hash_map.put( "4" , 15 );
li_hash_map.put( "Geeks" , 20 );
li_hash_map.put( "Welcomes" , 25 );
li_hash_map.put( "You" , 30 );
System.out.println( "Initial Mappings are: " + li_hash_map);
li_hash_map.clear();
System.out.println( "Finally the maps look like this: " + li_hash_map);
}
}
|
Output:
Initial Mappings are: {Geeks=20, 4=15, Welcomes=25, You=30}
Finally the maps look like this: {}
Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...