Properties putAll(Map) in Java

putAll(Map): This method is available in java.util.Properties class of Java.

Syntax:

void java.util.Properties.putAll(Map<?, ?> t)

This method takes one argument. This method copies all of the mappings from the specified map to this property. These mappings will replace any mappings that this property had for any of the keys currently in the specified map.

Parameters: One parameter is required for this method.

t: mappings to be stored in this map.

Throws:

NullPointerException - if the specified map is null

Approach 1: When no exception

Java

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

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

        Properties properties = new Properties();

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

        Map<String, String> t = new HashMap<String, String>();

        t.put("Hello", "World");
        t.put("C++", "Program");
        t.put("Python", "ML");

        properties.putAll(t);
        System.out.println(properties);
    }
}

Output:

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


Approach 2: NullPointerException

Java

import java.util.Map;
import java.util.Properties;

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

        Properties properties = new Properties();

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

        Map<String, String> t = null;

        properties.putAll(t);
        System.out.println(properties);
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Map.size()" because "m" is null at java.base/java.util.concurrent.ConcurrentHashMap.putAll(ConcurrentHashMap.java:1087) at java.base/java.util.Properties.putAll(Properties.java:1344)


No comments:

Post a Comment