HashTable compute() method in Java with Examples (original) (raw)

Last Updated : 2 Jun, 2023

The compute(Key, BiFunction) method of Hashtable class allows to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping is found).

Hashtable.compute(key, (k, v) -> v.append("strValue"))

Syntax:

public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

Parameters: This method accepts two parameters:

Returns: This method returns new value associated with the specified key, or null if none.

Exception: This method throws:

Below programs illustrate the compute(Key, BiFunction) method:

Program 1:

Java `

// Java program to demonstrate // compute(Key, BiFunction) method.

import java.util.*;

public class GFG {

// Main method
public static void main(String[] args)
{

    // create a table and add some values
    Map<String, Integer> table = new Hashtable<>();
    table.put("Pen", 10);
    table.put("Book", 500);
    table.put("Clothes", 400);
    table.put("Mobile", 5000);

    // print map details
    System.out.println("hashTable: " + table.toString());

    // remap the values of hashTable
    // using compute method
    table.compute("Pen", (key, val)
                             -> val + 15);
    table.compute("Clothes", (key, val)
                                 -> val - 120);

    // print new mapping
    System.out.println("new hashTable: " + table);
}

}

`

Output:

hashTable: {Book=500, Mobile=5000, Pen=10, Clothes=400} new hashTable: {Book=500, Mobile=5000, Pen=25, Clothes=280}

Program 2:

Java `

// Java program to demonstrate // compute(Key, BiFunction) method.

import java.util.*;

public class GFG {

// Main method
public static void main(String[] args)
{

    // create a table and add some values
    Map<Integer, String> table = new Hashtable<>();
    table.put(1, "100RS");
    table.put(2, "500RS");
    table.put(3, "1000RS");

    // print map details
    System.out.println("hashTable: "
                       + table.toString());

    // remap the values of hashTable
    // using compute method
    table.compute(3, (key, val)
                         -> val.substring(0, 4) + "00RS");
    table.compute(2, (key, val)
                         -> val.substring(0, 2) + "$");

    // print new mapping
    System.out.println("new hashTable: " + table);
}

}

`