Map put() Method in Java with Examples
The Map put() method associates the specified value with the specified key in the map. The map put() method is used to insert new key-value pairs inside a map in Java.
If the map already contains the mapping for the specified key, the old value is replaced by the new specified value.
Example:
Java
import java.util.HashMap;
import java.util.Map;
public class MapPutExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put( "One" , 1 );
map.put( "Two" , 2 );
System.out.println( "Map after adding elements: " + map);
Integer oldValue = map.put( "Two" , 22 );
System.out.println( "Previous value for key 'Two': " + oldValue);
System.out.println( "Map after updating 'Two': " + map);
}
}
|
Output:
Map after adding elements: {One=1, Two=2}
Previous value for key 'Two': 2
Map after updating 'Two': {One=1, Two=22}
Syntax
V put(K key, V value)
Parameters
This method has two arguments, key and value where the key is the left argument and the value is the corresponding value of the key in the map.
Returns
Returns the previous value associated with the key if present, else returns a null value.
Exceptions
- NullPointerException– When the specified key is null
- ClassCastException- When the type of key-value pair is incompatible with the map.
Map put() Method Examples
Let’s see some examples of how to use the map put() method:
Example 1
How to insert/add elements in a map using the map put() method:
Java
import java.util.*;
public class GfG {
public static void main(String[] args)
{
Map<Integer, String> map = new HashMap<>();
map.put( 1 , "One" );
map.put( 3 , "Three" );
map.put( 5 , "Five" );
map.put( 7 , "Seven" );
map.put( 9 , "Nine" );
System.out.println(map);
}
}
|
Output
{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}
Example 2
Below is the code to show the implementation of put().
Java
import java.util.*;
public class GfG {
public static void main(String[] args)
{
Map<String, String> map = new HashMap<>();
map.put( "1" , "One" );
map.put( "3" , "Three" );
map.put( "5" , "Five" );
map.put( "7" , "Seven" );
map.put( "9" , "Nine" );
System.out.println(map);
}
}
|
Output
{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}
Read More Map Methods
Whether you are a beginner starting Java programming or an experienced looking to brush up on your Java skills, this tutorial will provide you with a deep understanding of the map put function and its uses in Java.
The map put method in Java is a fundamental function for map manipulation. With this guide, you can easily add new key-value pairs using the map put function.
Last Updated :
16 Feb, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...