ConcurrentMap's replace(k,Old v, New v) method in Java.

ConcurrentMap's replace(k,Old v, New v) method in Java.


Posted in : Core Java Posted on : March 10, 2011 at 7:50 PM Comments : [ 0 ]

In this tutorial we will discuss how can replace(k, Old v, New v) method be implemented in ConcurrentMap interface in java. boolean replace(K key,V oldValue,V newValue) This method replaces the old mapping with specified new mapping for a key if presently associated to given value.

ConcurrentMap's replace(k,Old v, New v) method in Java.

In this tutorial we will discuss how can replace(k, Old v, New v) method be implemented in ConcurrentMap interface in java.

Syntax

boolean replace(K key,V oldValue,V newValue)

This function replaces the old mapping with specified new mapping for a key if presently associated to given value.

The core work of this method is to replace an old value with new value. Internally this function first do test for the key whether it is presently mapped into the map, if it is true then it puts the new value in place of the old value which is previously associated with the key and returns the previously associated (old) value otherwise, returns 'null' if there were no association for the key. If this function gives back 'null' it does not only mean that the map has no mapping for a particular key this can also meant that the particular key is associated with 'null' value.

Parameter description

k : It is the key with which the given value is associated.

Old v : It is the value which the map antecedently associated with the specified key.

New v : It is the value to be associated with the particular key.

Example of replace(k,Old v, New v) method

In this example we will discuss how does replace(k,Old v,New v) method work in ConcurrentMap interface. This example will help you to understand how can you replace an old value with new value.

Example :

package devmanuals.com;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentHashMap;
public class CMReplaceOld {
  public static void main(String[] args) {
    ConcurrentMap cmp = new ConcurrentHashMap();
    cmp.put("Rose", "India");
    cmp.put("Dev", "Manuals");
    cmp.put("News", "Track");
    System.out.println("Mappings = " + cmp);
    System.out.println("Size of map = "+cmp.size());
    System.out.println("Set of keys = "+cmp.keySet());
    boolean bol = cmp.replace("Dev", "Manuals", "Manuals.com");
    System.out.println("Value is replaced : " + bol);
    System.out.println("New mappings after replacing with \n \tnew value : "+ cmp);
  }
}

Output :

Mappings = {News=Track, Dev=Manuals, Rose=India}

Size of map = 3

Set of keys = [News, Dev, Rose]

Value is replaced : true

New mappings after replacing with

new value : {News=Track, Dev=Manuals.com, Rose=India}

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics