Properties computeIfPresent(Object, BiFunction) in Java

computeIfPresent(Object, BiFunction): This method is available in java.util.Properties class of Java.

Syntax:

Object java.util.Properties.computeIfPresent(Object key, BiFunction<? super Object, ? super Object, ?> remappingFunction)

This method takes two arguments. If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.

Parameters: Two parameters are required for this method.

key: key with which the specified value is to be associated.

remappingFunction: the remapping function to compute a value.

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

Throws:

NullPointerException - if the specified key is null and this map does not support null keys, or the remappingFunction is null.

Approach 1: When no exception 

Java

import java.util.Properties;
import java.util.function.BiFunction;

public class PropertiescomputeIfPresent {
    public static void main(String[] args) {

        Properties properties = new Properties();

        properties.put("Hello", "World");
        properties.put("C++", "Program");
        properties.put("Java", "Program");

        Object key = "Hello";
        BiFunction<? super Object, ? super Object,
?> remappingFunction = (a, b) -> a;

        properties.computeIfPresent(key, remappingFunction);

        System.out.println(properties);
    }
}

Output:

{Java=Program, C++=Program, Hello=Hello}


Approach 2: NullPointerException

Java

import java.util.Properties;
import java.util.function.BiFunction;

public class PropertiescomputeIfPresent {
    public static void main(String[] args) {

        Properties properties = new Properties();

        properties.put("Hello", "World");
        properties.put("C++", "Program");
        properties.put("Java", "Program");

        Object key = null;
        BiFunction<? super Object, ? super Object,
?> remappingFunction = (a, b) -> a;

        properties.computeIfPresent(key, remappingFunction);

        System.out.println(properties);
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.concurrent.ConcurrentHashMap.computeIfPresent(ConcurrentHashMap.java:1805) at java.base/java.util.Properties.computeIfPresent(Properties.java:1477)


No comments:

Post a Comment