Java HashMap Compute() Method

Java HashMap Compute() Method

Java HashMap

  • The compute() method in Java HashMap class is used to compute the value for a given key using the given remapping function.
  • This method takes two parameters:
    • key: This parameter is of the key type, which is used to find the value in the HashMap.
    • remapping Function: This is a functional interface that is used to compute the new value for the key. It takes two parameters – key and value and returns the new value.
  • To understand the Java HashMap Compute() Method, Read the Complete Article.

The compute() method performs the following operations:

  • Here are the methods to perform following operations: 
  • It checks whether the key is present in the HashMap or not. If the key is not present, then it returns null.
  • If the key is present, then it computes the new value using the given remapping function.
  • If the new value is null, then it removes the mapping for the key from the HashMap.
  • If the new value is not null, then it replaces the old value with the new value.
Java HashMap Compute()

Let’s look at the Java HashMap compute() Method to perform certain operations.

Example 1: Java Program to run use compute Method.

Run

import java.util.HashMap;

public class Main {

    public static void main(String[] args) {
        // Create a HashMap with some initial mappings
        HashMap<String, Integer> map = new HashMap<>();
        map.put("ayush", 1);
        map.put("ashish", 2);

        // Insert a new value using the compute() method
        map.compute("anjali", (key, value) -> value == null ? 3 : value);

        // Print the updated HashMap
        System.out.println(map);
    }
}

Output

{ashish=2, anjali=3, ayush=1}

Example 2 :Java Program to use Compute() Method

Run

import java.util.HashMap;

 
public class Main
{
  
 
public static void main (String[]args)
  {
    
      // Create a HashMap with some initial mappings
      HashMap < String, Integer > map = new HashMap <> ();
    
map.put ("Cricket", 1);
    
map.put ("Football", 2);
    
 
      // Insert a new value using the compute() method
      map.compute ("Basketball", (key, value)->value == null ? 3 : value);
    
 
      // Print the updated HashMap
      System.out.println (map);

} 
} 

Output

{Cricket=1, Basketball=3, Football=2}

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription