HashMap in Java

HashMap in Java

HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of Map interface of Java. It stores the data in (Key, Value) pairs. To access a value one must know its key. HashMap is known as HashMap because it uses a technique called Hashing.Hashing is a technique of converting a large String to small String that represents same String. A shorter value helps in indexing and faster searches. HashSet also uses HashMap internally. It internally uses a link list to store key-value pairs already explained in HashSet in detail and further articles. HashMap实现了map的接口,以(key,value)的方式存储数据,获得value必须知道key,之所以叫hashmap,是使用了hashing,hashing技术把大的string转成小的string,但表示同一个string。hashset也使用hashmap实现。
Few important features of HashMap are:

  • HashMap is a part of java.util package.
  • HashMap extends an abstract class AbstractMap which also provides an incomplete implementation of Map interface.
  • It also implements Cloneable and Serializable interface. K and V in the above definition represent Key and Value respectively.
  • HashMap doesn’t allow duplicate keys but allows duplicate values. That means A single key can’t contain more than 1 value but more than 1 key can contain a single value.  HashMap不允许重复的key,但允许重复的value,
  • HashMap allows null key also but only once and multiple null values.
  • This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. It is roughly similar to HashTable but is unsynchronized.

Internal Structure of HashMap

Internally HashMap contains an array of Node and a node is represented as a class which contains 4 fields :

  1. int hash
  2. K key
  3. V value
  4. Node next

It can be seen that node is containing a reference of its own object. So it’s a linked list.
HashMap:
array

Node :
node_hash_map

Performance of HashMap

Performance of HashMap depends on 2 parameters:

  1. Initial Capacity
  2. Load Factor

As already said, Capacity is simply the number of buckets whereas the Initial Capacity is the capacity of HashMap instance when it is created. The Load Factor is a measure that when rehashing should be done. Rehashing is a process of increasing the capacity. In HashMap capacity is multiplied by 2. Load Factor is also a measure that what fraction of the HashMap is allowed to fill before rehashing. When the number of entries in HashMap increases the product of current capacity and load factor the capacity is increased that is rehashing is done. If the initial capacity is kept higher then rehashing will never be done. But by keeping it higher it increases the time complexity of iteration. So it should be choosed very cleverly to increase the performance. The expected number of values should be taken into account to set initial capacity. Most generally preffered load factor value is 0.75 which provides a good deal between time and space costs. Load factor’s value varies between 0 and 1.

Synchronized HashMap

As it is told that HashMap is unsynchronized i.e. multiple threads can access it simultaneously. If multiple threads access this class simultaneously and at least one thread manipulates it structurally then it is necessary to make it synchronized externally. It is done by synchronizing some object which enzapsulates the map. If No such object exists then it can be wrapped around Collections.synchronizedMap() to make HashMap synchronized and avoid accidental unsynchronized access. As in following example:

Map m = Collections.synchronizedMap(new HashMap(...));

Now the Map m is synchronized.

Iterators of this class are fail-fast if any structure modification is done after creation of iterator, in any way except through the iterator’s remove method. In faliure of iterator it will throw ConcurrentModificationException.

Constructors in HashMap

HashMap provides 4 constructors and access modifier of each is public:

  1. HashMap() : It is the default constructor which creates an instance of HashMap with initial capacity 16 and load factor 0.75.
  2. HashMap(int initial capacity) : It creates a HashMap instance with specified initial capacity and load factor 0.75.
  3. HashMap(int initial capacity, float loadFactor) : It creates a HashMap instance with specified initial capacity and specified load factor.
  4. HashMap(Map map) : It creates instance of HashMapwith same mappings as specified map.

Example:



// Java program to illustrate 
// Java.util.HashMap 
import java.util.HashMap; 
import java.util.Map; 

public class GFG 
{ 
	public static void main(String[] args) 
	{ 
	
		HashMap<String, Integer> map = new HashMap<>(); 
		
		print(map); 
		map.put("vishal", 10); 
		map.put("sachin", 30); 
		map.put("vaibhav", 20); 
		
		System.out.println("Size of map is:- " + map.size()); 
	
		print(map); 
		if (map.containsKey("vishal")) 
		{ 
			Integer a = map.get("vishal"); 
			System.out.println("value for key \"vishal\" is:- " + a); 
		} 
		
		map.clear(); 
		print(map); 
	} 
	
	public static void print(Map<String, Integer> map) 
	{ 
		if (map.isEmpty()) 
		{ 
			System.out.println("map is empty"); 
		} 
		
		else
		{ 
			System.out.println(map); 
		} 
	} 
} 

Output:

map is empty
Size of map is:- 3
{vaibhav=20, vishal=10, sachin=30}
value for key "vishal" is:- 10
map is empty

Time complexity of HashMap

HashMap provides constant time complexity for basic operations, get and put, if hash function is properly written and it disperses the elements properly among the buckets. Iteration over HashMap depends on the capacity of HashMap and number of key-value pairs. Basically it is directly proportional to the capacity + size. Capacity is the number of buckets in HashMap. So it is not a good idea to keep high number of buckets in HashMap initially.

Methods in HashMap

  1. void clear(): Used to remove all mappings from a map.
  2. boolean containsKey(Object key): Used to return True if for a specified key, mapping is present in the map.
  3. boolean containsValue(Object value): Used to return true if one or more key is mapped to a specified value.
  4. Object clone(): It is used to return a shallow copy of the mentioned hash map.
  5. boolean isEmpty(): Used to check whether the map is empty or not. Returns true if the map is empty.
  6. Set entrySet(): It is used to return a set view of the hash map.
  7. Object get(Object key): It is used to retrieve or fetch the value mapped by a particular key.
  8. Set keySet(): It is used to return a set view of the keys.
  9. int size(): It is used to return the size of a map.
  10. Object put(Object key, Object value): It is used to insert a particular mapping of key-value pair into a map.
  11. putAll(Map M): It is used to copy all of the elements from one map into another.
  12. Object remove(Object key): It is used to remove the values for any particular key in the Map.
  13. Collection values(): It is used to return a Collection view of the values in the HashMap.

Related Articles:

  • Hashmap vs Treemap
  • Hashmap vs HashTable
  • compute​(K key, BiFunction<K,V> remappingFunction): This method Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
  • computeIfAbsent​(K key, Function<K> mappingFunction): This method If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
  • computeIfPresent​(K key, BiFunction<K,V> remappingFunction): This method If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
  • forEach​(BiConsumer<K,V> action): This method Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
  • getOrDefault​(Object key, V defaultValue): This method returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
  • merge​(K key, V value, BiFunction<K,V> remappingFunction): This method If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
  • putIfAbsent​(K key, V value): This method If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
  • replace​(K key, V value): This method replaces the entry for the specified key only if it is currently mapped to some value.
  • replace​(K key, V oldValue, V newValue): This method replaces the entry for the specified key only if currently mapped to the specified value.
  • replaceAll​(BiFunction<K,V> function): This method replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.

HashMap clear() Method in Java

The java.util.HashMap.clear() method in Java is used to clear and remove all of the elements or mappings from a specified HashMap.

Syntax:

Hash_Map.clear()

Parameters: The method does not accept any parameters.

Return Value: The method does not return any value.

Below programs are used to illustrate the working of java.util.HashMap.clear() Method:
Program 1: Mapping String Values to Integer Keys.

// Java code to illustrate the clear() method 
import java.util.*; 

public class Hash_Map_Demo { 
	public static void main(String[] args) 
	{ 

		// Creating an empty HashMap 
		HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); 

		// Mapping string values to int keys 
		hash_map.put(10, "Geeks"); 
		hash_map.put(15, "4"); 
		hash_map.put(20, "Geeks"); 
		hash_map.put(25, "Welcomes"); 
		hash_map.put(30, "You"); 

		// Displaying the HashMap 
		System.out.println("Initial Mappings are: " + hash_map); 

		// Clearing the hash map using clear() 
		hash_map.clear(); 

		// Displaying the final HashMap 
		System.out.println("Finally the maps look like this: " + hash_map); 
	} 
} 

Output:

Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Finally the maps look like this: {}

Program 2: Mapping Integer Values to String Keys.

// Java code to illustrate the clear() method 
import java.util.*; 

public class Hash_Map_Demo { 
	public static void main(String[] args) 
	{ 

		// Creating an empty HashMap 
		HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); 

		// Mapping int values to string keys 
		hash_map.put("Geeks", 10); 
		hash_map.put("4", 15); 
		hash_map.put("Geeks", 20); 
		hash_map.put("Welcomes", 25); 
		hash_map.put("You", 30); 

		// Displaying the HashMap 
		System.out.println("Initial Mappings are: " + hash_map); 

		// Clearing the hash map using clear() 
		hash_map.clear(); 

		// Displaying the final HashMap 
		System.out.println("Finally the maps look like this: " + hash_map); 
	} 
} 

Output:

Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
Finally the maps look like this: {}

Note: The same operation can be performed with any type of Mapping with variation and combination of different data types.

HashMap containsKey() Method in Java

The java.util.HashMap.containsKey() method is used to check whether a particular key is being mapped into the HashMap or not. It takes the key element as a parameter and returns True if that element is mapped in the map.

Syntax:

Hash_Map.containsKey(key_element)

Parameters: The method takes just one parameter key_element that refers to the key whose mapping is supposed to be checked inside a map.

Return Value: The method returns boolean true if the presence of the key is detected else false .

Below programs are used to illustrate the working of java.util.HashMap.containsKey() Method:
Program 1: Mapping String Values to Integer Keys.

// Java code to illustrate the containsKey() method 
import java.util.*; 

public class Hash_Map_Demo { 
	public static void main(String[] args) 
	{ 

		// Creating an empty HashMap 
		HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); 

		// Mapping string values to int keys 
		hash_map.put(10, "Geeks"); 
		hash_map.put(15, "4"); 
		hash_map.put(20, "Geeks"); 
		hash_map.put(25, "Welcomes"); 
		hash_map.put(30, "You"); 

		// Displaying the HashMap 
		System.out.println("Initial Mappings are: " + hash_map); 

		// Checking for the key_element '20' 
		System.out.println("Is the key '20' present? " + 
		hash_map.containsKey(20)); 

		// Checking for the key_element '5' 
		System.out.println("Is the key '5' present? " + 
		hash_map.containsKey(5)); 
	} 
} 

Output:

Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Is the key '20' present? true
Is the key '5' present? false

Program 2: Mapping Integer Values to String Keys.

// Java code to illustrate the containsKey() method 
import java.util.*; 

public class Hash_Map_Demo { 
	public static void main(String[] args) 
	{ 

		// Creating an empty HashMap 
		HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); 

		// Mapping int values to string keys 
		hash_map.put("Geeks", 10); 
		hash_map.put("4", 15); 
		hash_map.put("Geeks", 20); 
		hash_map.put("Welcomes", 25); 
		hash_map.put("You", 30); 

		// Displaying the HashMap 
		System.out.println("Initial Mappings are: " + hash_map); 

		// Checking for the key_element 'Welcomes' 
		System.out.println("Is the key 'Welcomes' present? " + 
		hash_map.containsKey("Welcomes")); 

		// Checking for the key_element 'World' 
		System.out.println("Is the key 'World' present? " + 
		hash_map.containsKey("World")); 
	} 
} 

Output:

Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
Is the key 'Welcomes' present? true
Is the key 'World' present? false

Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.

HashMap containsValue() Method in Java

The java.util.HashMap.containsValue() method is used to check whether a particular value is being mapped by a single or more than one key in the HashMap. It takes the Value as a parameter and returns True if that value is mapped by any of the key in the map.

Syntax:

Hash_Map.containsValue(Object Value)

Parameters: The method takes just one parameter Value of Object type and refers to the value whose mapping is supposed to be checked by any key inside the map.

Return Value: The method returns boolean true if the mapping of the value is detected else false.

Below programs are used to illustrate the working of java.util.HashMap.containsValue() Method:
Program 1: Mapping String Values to Integer Keys.

// Java code to illustrate the containsValue() method 
import java.util.*; 

public class Hash_Map_Demo { 
	public static void main(String[] args) 
	{ 

		// Creating an empty HashMap 
		HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); 

		// Mapping string values to int keys 
		hash_map.put(10, "Geeks"); 
		hash_map.put(15, "4"); 
		hash_map.put(20, "Geeks"); 
		hash_map.put(25, "Welcomes"); 
		hash_map.put(30, "You"); 

		// Displaying the HashMap 
		System.out.println("Initial Mappings are: " + hash_map); 

		// Checking for the Value 'Geeks' 
		System.out.println("Is the value 'Geeks' present? " + 
		hash_map.containsValue("Geeks")); 

		// Checking for the Value 'World' 
		System.out.println("Is the value 'World' present? " + 
		hash_map.containsValue("World")); 
	} 
} 

Output:

Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Is the value 'Geeks' present? true
Is the value 'World' present? false

Program 2: Mapping Integer Values to String Keys.

// Java code to illustrate the containsValue() method 
import java.util.*; 

public class Hash_Map_Demo { 
	public static void main(String[] args) 
	{ 

		// Creating an empty HashMap 
		HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); 

		// Mapping int values to string keys 
		hash_map.put("Geeks", 10); 
		hash_map.put("4", 15); 
		hash_map.put("Geeks", 20); 
		hash_map.put("Welcomes", 25); 
		hash_map.put("You", 30); 

		// Displaying the HashMap 
		System.out.println("Initial Mappings are: " + hash_map); 

		// Checking for the Value '10' 
		System.out.println("Is the value '10' present? " + 
		hash_map.containsValue(10)); 

		// Checking for the Value '30' 
		System.out.println("Is the value '30' present? " + 
		hash_map.containsValue(30)); 

		// Checking for the Value '40' 
		System.out.println("Is the value '40' present? " + 
		hash_map.containsValue(40)); 
	} 
} 

Output:

Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
Is the value '10' present? false
Is the value '30' present? true
Is the value '40' present? false

Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.

HashMap isEmpty() Method in Java

The java.util.HashMap.isEmpty() method of HashMap class is used to check for the emptiness of the map. The method returns True if no key-value pair or mapping is present in the map else False.

Syntax:

Hash_Map.isEmpty()

Parameters: The method does not take any parameters.

Return Value: The method returns boolean true if the map is empty or does not contain any mapping pairs else boolean false.

Below programs illustrates the working of java.util.HashMap.isEmpty() method:
Program 1: Mapping String Values to Integer Keys.

// Java code to illustrate the isEmpty() method 
import java.util.*; 

public class Hash_Map_Demo { 
	public static void main(String[] args) 
	{ 

		// Creating an empty HashMap 
		HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); 

		// Mapping int values to string keys 
		hash_map.put("Geeks", 10); 
		hash_map.put("4", 15); 
		hash_map.put("Geeks", 20); 
		hash_map.put("Welcomes", 25); 
		hash_map.put("You", 30); 

		// Displaying the HashMap 
		System.out.println("The Mappings are: " + hash_map); 

		// Checking for the emptiness of Map 
		System.out.println("Is the map empty? " + hash_map.isEmpty()); 
	} 
} 

Output:

The Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
Is the map empty? false

Program 2: For an empty HashMap

// Java code to illustrate the isEmpty() method 
import java.util.*; 

public class Hash_Map_Demo { 
	public static void main(String[] args) 
	{ 

		// Creating an empty HashMap 
		HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); 

		// Displaying the HashMap 
		System.out.println("The Mappings are: " + hash_map); 

		// Checking for the emptiness of Map 
		System.out.println("Is the map empty? " + hash_map.isEmpty()); 
	} 
} 

Output:

The Mappings are: {}
Is the map empty? true

Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.

HashMap get() Method in Java

The java.util.HashMap.get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.

Syntax:

Hash_Map.get(Object key_element)

Parameter: The method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched.

Return Value: The method returns the value associated with the key_element in the parameter.

Below programs illustrates the working of java.util.HashMap.get() method:
Program 1: Mapping String Values to Integer Keys.

// Java code to illustrate the get() method 
import java.util.*; 

public class Hash_Map_Demo { 
	public static void main(String[] args) 
	{ 

		// Creating an empty HashMap 
		HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); 

		// Mapping string values to int keys 
		hash_map.put(10, "Geeks"); 
		hash_map.put(15, "4"); 
		hash_map.put(20, "Geeks"); 
		hash_map.put(25, "Welcomes"); 
		hash_map.put(30, "You"); 

		// Displaying the HashMap 
		System.out.println("Initial Mappings are: " + hash_map); 

		// Getting the value of 25 
		System.out.println("The Value is: " + hash_map.get(25)); 

		// Getting the value of 10 
		System.out.println("The Value is: " + hash_map.get(10)); 
	} 
} 

Output:

Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
The Value is: Welcomes
The Value is: Geeks

Program 2: Mapping Integer Values to String Keys.

// Java code to illustrate the get() method 
import java.util.*; 

public class Hash_Map_Demo { 
	public static void main(String[] args) 
	{ 

		// Creating an empty HashMap 
		HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); 

		// Mapping int values to string keys 
		hash_map.put("Geeks", 10); 
		hash_map.put("4", 15); 
		hash_map.put("Geeks", 20); 
		hash_map.put("Welcomes", 25); 
		hash_map.put("You", 30); 

		// Displaying the HashMap 
		System.out.println("Initial Mappings are: " + hash_map); 

		// Getting the value of "Geeks" 
		System.out.println("The Value is: " + hash_map.get("Geeks")); 

		// Getting the value of "You" 
		System.out.println("The Value is: " + hash_map.get("You")); 
	} 
} 

Output:

Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
The Value is: 20
The Value is: 30

Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.

HashMap size() Method in Java

The java.util.HashMap.size() method of HashMap class is used to get the size of the map which refers to the number of the key-value pair or mappings in the Map.

Syntax:

Hash_Map.size()

Parameters: The method does not take any parameters.

Return Value: The method returns the size of the map which also means the number of key-value pairs present in the map.

Below programs illustrates the working of java.util.HashMap.size():
Program 1: Mapping String Values to Integer Keys.

// Java code to illustrate the size() method 
import java.util.*; 

public class Hash_Map_Demo { 
	public static void main(String[] args) 
	{ 

		// Creating an empty HashMap 
		HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); 

		// Mapping string values to int keys 
		hash_map.put(10, "Geeks"); 
		hash_map.put(15, "4"); 
		hash_map.put(20, "Geeks"); 
		hash_map.put(25, "Welcomes"); 
		hash_map.put(30, "You"); 

		// Displaying the HashMap 
		System.out.println("Initial Mappings are: " + hash_map); 

		// Displaying the size of the map 
		System.out.println("The size of the map is " + hash_map.size()); 
	} 
} 

Output:

Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
The size of the map is 5

Program 2: Mapping Integer Values to String Keys.

// Java code to illustrate the size() method 
import java.util.*; 

public class Hash_Map_Demo { 
	public static void main(String[] args) 
	{ 

		// Creating an empty HashMap 
		HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); 

		// Mapping int values to string keys 
		hash_map.put("Geeks", 10); 
		hash_map.put("4", 15); 
		hash_map.put("Geeks", 20); 
		hash_map.put("Welcomes", 25); 
		hash_map.put("You", 30); 

		// Displaying the HashMap 
		System.out.println("Initial Mappings are: " + hash_map); 

		// Displaying the size of the map 
		System.out.println("The size of the map is " + hash_map.size()); 
	} 
} 

Output:

Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
The size of the map is 4

Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.

HashMap put() Method in Java

The java.util.HashMap.put() method of HashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to into a particular map. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.

Syntax:

Hash_Map.put(key, value)

Parameters: The method takes two parameters, both are of the Object type of the HashMap.

  • key: This refers to the key element that needs to be inserted into the Map for mapping.
  • value: This refers to the value that the above key would map into.

Return Value: If an existing key is passed then the previous value gets returned. If a new pair is passed, then NULL is returned.

Below programs are used to illustrate the working of java.util.HashMap.put() Method:
Program 1: When passing an existing key.

// Java code to illustrate the put() method 
import java.util.*; 

public class Hash_Map_Demo { 
	public static void main(String[] args) 
	{ 

		// Creating an empty HashMap 
		HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); 

		// Mapping string values to int keys 
		hash_map.put(10, "Geeks"); 
		hash_map.put(15, "4"); 
		hash_map.put(20, "Geeks"); 
		hash_map.put(25, "Welcomes"); 
		hash_map.put(30, "You"); 

		// Displaying the HashMap 
		System.out.println("Initial Mappings are: " + hash_map); 

		// Inserting existing key along with new value 
		String returned_value = (String)hash_map.put(20, "All"); 

		// Verifying the returned value 
		System.out.println("Returned value is: " + returned_value); 

		// Displayin the new map 
		System.out.println("New map is: " + hash_map); 
	} 
} 

Output:

Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Returned value is: Geeks
New map is: {20=All, 25=Welcomes, 10=Geeks, 30=You, 15=4}

Program 2: When passing a new key.

// Java code to illustrate the put() method 
import java.util.*; 

public class Hash_Map_Demo { 
	public static void main(String[] args) 
	{ 

		// Creating an empty HashMap 
		HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); 

		// Mapping string values to int keys 
		hash_map.put(10, "Geeks"); 
		hash_map.put(15, "4"); 
		hash_map.put(20, "Geeks"); 
		hash_map.put(25, "Welcomes"); 
		hash_map.put(30, "You"); 

		// Displaying the HashMap 
		System.out.println("Initial Mappings are: " + hash_map); 

		// Inserting existing key along with new value 
		String returned_value = (String)hash_map.put(50, "All"); 

		// Verifying the returned value 
		System.out.println("Returned value is: " + returned_value); 

		// Displayin the new map 
		System.out.println("New map is: " + hash_map); 
	} 
} 

Output:

Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Returned value is: null
New map is: {50=All, 20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}

Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.

HashMap remove() Method in Java

The java.util.HashMap.remove() is an inbuilt method of HashMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map.

Syntax:

Hash_Map.remove(Object key)

Parameters: The method takes one parameter key whose mapping is to be removed from the Map.

Return Value: The method returns the value that was previously mapped to the specified key if the key exists else the method returns NULL.

Below programs illustrates the working of java.util.HashMap.remove() method:
Program 1: When passing an existing key.

// Java code to illustrate the remove() method 
import java.util.*; 

public class Hash_Map_Demo { 
public static void main(String[] args) { 
		
	// Creating an empty HashMap 
	HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); 

	// Mapping string values to int keys 
	hash_map.put(10, "Geeks"); 
	hash_map.put(15, "4"); 
	hash_map.put(20, "Geeks"); 
	hash_map.put(25, "Welcomes"); 
	hash_map.put(30, "You"); 

	// Displaying the HashMap 
	System.out.println("Initial Mappings are: " + hash_map); 

	// Removing the existing key mapping 
	String returned_value = (String)hash_map.remove(20); 

	// Verifying the returned value 
	System.out.println("Returned value is: "+ returned_value); 

	// Displayin the new map 
	System.out.println("New map is: "+ hash_map); 
} 
} 

Output:

Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Returned value is: Geeks
New map is: {25=Welcomes, 10=Geeks, 30=You, 15=4}

Program 2: When passing a new key.

// Java code to illustrate the remove() method 
import java.util.*; 
	
public class Hash_Map_Demo { 
public static void main(String[] args) { 
		
	// Creating an empty HashMap 
	HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); 
	
	// Mapping string values to int keys 
	hash_map.put(10, "Geeks"); 
	hash_map.put(15, "4"); 
	hash_map.put(20, "Geeks"); 
	hash_map.put(25, "Welcomes"); 
	hash_map.put(30, "You"); 

	// Displaying the HashMap 
	System.out.println("Initial Mappings are: " + hash_map); 

	// Removing the new key mapping 
	String returned_value = (String)hash_map.remove(50); 

	// Verifying the returned value 
	System.out.println("Returned value is: "+ returned_value); 

	// Displayin the new map 
	System.out.println("New map is: "+ hash_map); 
} 
} 

Output:

Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Returned value is: null
New map is: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}

Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.

猜你喜欢

转载自blog.csdn.net/qq_27009517/article/details/86676569