Search code examples
javanullpointerexceptionhashmap

Getting "null" value from map


I have HashMap:

Map<String, Object> second = new HashMap<>(Map.of("timeout", 20, "verbose", null, "host", "test"));

And the second map with no null value. I put their .keyset() to Set and then starting parse. And when i`m trying to parse it:

 if (firstMap.containsKey(s) && secondMap.containsKey(s) && !Objects.equals(firstMap.get(s), secondMap.get(s))) {
            diffList.add(Map.of(s, "changed", "oldValue", firstMap.get(s), "newValue", secondMap.get(s)));
        }

I get NPE. I understand why, but i cant understand how i can fix that. I saw similar posts, but it doesnt help me.

Exception in thread "main" java.lang.NullPointerException
at java.base/java.util.Objects.requireNonNull(Objects.java:208)
at java.base/java.util.ImmutableCollections$MapN.<init>(ImmutableCollections.java:1186)
at java.base/java.util.Map.of(Map.java:1351)
at com.company.Main.main(Main.java:13)

Solution

  • Map.of does not allow null values. To quote the Javadoc:

    Unmodifiable Maps
    They disallow null keys and values. Attempts to create them with null keys or values result in NullPointerException.

    Instead, you can directly call put.

    Map<String, Object> second = new HashMap<>();  // `HashMap` permits null values and null key.
    second.put("timeout", 20);
    second.put("verbose", null);
    second.put("host", "test");