Properties computeIfAbsent(Object, Function) in Java

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

Syntax:

Object java.util.Properties.computeIfAbsent(Object key, Function<? super Object, ?> mappingFunction)

This method takes two arguments. If the specified key is not already associated with a value attempt to compute its value using the given mapping function and enter it into this property unless null.

Parameters: Two parameters are required for this method.

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

mappingFunction: the mapping function to compute a value.

Returns: the current value associated with the specified key, or null if the computed value is null.

Throws:

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

Approach 1: When no exception

Java

import java.util.Properties;
import java.util.function.Function;

public class PropertiescomputeIfAbsent {
    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";
        Function<? super String, ?> mappingFunction = a -> a;
        properties.computeIfAbsent(key, (Function<?
super Object, ?>) mappingFunction);
        System.out.println(properties.clone());
    }
}

Output:

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


Approach 2: NullPointerException 

Java

import java.util.Properties;
import java.util.function.Function;

public class PropertiescomputeIfAbsent {
    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;
        Function<? super String, ?> mappingFunction = a -> a;
        properties.computeIfAbsent(key, (Function<?
super Object, ?>) mappingFunction);
        System.out.println(properties.clone());
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1693) at java.base/java.util.Properties.computeIfAbsent(Properties.java:1471)


No comments:

Post a Comment