Properties compute(Object, BiFunction) in Java

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

Syntax:

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

This method takes two arguments. This method computes the values according to the mapping function.

Parameters: Two parameters are required for this method.

key: the key to computing.

remappingFunction: mapping function.

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

Throws:

NullPointerException - if the specified key is null or the remapping function is null.

Approach 1: When no exception

Java

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

public class Propertiescompute {
    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.compute(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 Propertiescompute {
    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.compute(key, remappingFunction);

        System.out.println(properties);
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.concurrent.ConcurrentHashMap.compute(ConcurrentHashMap.java:1900) at java.base/java.util.Properties.compute(Properties.java:1483)


No comments:

Post a Comment