HashMap replace(key, oldValue, newValue) method in Java with Examples
The replace(K key, V oldValue, V newValue) method of Map interface, implemented by HashMap class is used to replace the old value of the specified key only if the key is previously mapped with the specified old value.
Syntax:
default boolean replace(K key, V oldValue, V newValue)
Parameters: This method accepts three parameters :
- key: which is the key of the element whose value has to be replaced.
- oldValue: which is the old value which has to be mapped with the provided key.
- newValue: which is the new value which has to be mapped with the specified key.
Return Value: This method returns boolean value true if old value was replaced, otherwise false.
Exceptions: This method will throw:
- NullPointerException if the specified key or value is null, and this map does not permit null keys or values and
- IllegalArgumentException if some property of the specified key or value prevents it from being stored in this map.
Program 1:
import java.util.*;
public class GFG {
public static void main(String[] args)
{
HashMap<String, Integer> map
= new HashMap<>();
map.put( "a" , 100 );
map.put( "b" , 300 );
map.put( "c" , 300 );
map.put( "d" , 400 );
System.out.println( "HashMap: "
+ map.toString());
map.replace( "b" , 300 , 200 );
System.out.println( "New HashMap: "
+ map.toString());
}
}
|
Output:
HashMap: {a=100, b=300, c=300, d=400}
New HashMap: {a=100, b=200, c=300, d=400}
Program 2:
import java.util.*;
public class GFG {
public static void main(String[] args)
{
HashMap<String, Integer> map
= new HashMap<>();
map.put( "a" , 100 );
map.put( "b" , 300 );
map.put( "c" , 300 );
map.put( "d" , 400 );
System.out.println( "HashMap: "
+ map.toString());
boolean isReplaced = map.replace( "b" , 200 , 500 );
System.out.println( "Old value for 'b' was "
+ "replaced: " + isReplaced);
System.out.println( "New HashMap: "
+ map.toString());
}
}
|
Output:
HashMap: {a=100, b=300, c=300, d=400}
Old value for 'b' was replaced: false
New HashMap: {a=100, b=300, c=300, d=400}
References: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#replace-K-V-V-
Last Updated :
28 Oct, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...