Skip to content

UseMapOf converts HashMap with null keys/values to Map.of() which throws NullPointerException #1092

Closed

Description

@protocol7

What version of OpenRewrite are you using?

  • rewrite-migrate-java: 3.34.0
  • rewrite-core: 8.81.6
  • rewrite-java: 8.81.6

What is the smallest, simplest way to reproduce the problem?

package com.helloworld;

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

public class Main {
  Map<String, String> createWithNullValue() {
    return new HashMap<>() {
      {
        put("key", "value");
        put("nullable", null);
      }
    };
  }

  Map<String, String> createWithNullKey() {
    return new HashMap<>() {
      {
        put(null, "value");
        put("key", "other");
      }
    };
  }
}

Run org.openrewrite.java.migrate.util.UseMapOf.

What did you expect to see?

No change. The maps contain null values/keys, and Map.of() does not permit null keys or values, so the transformation is not semantics-preserving.

What did you see instead?

The recipe rewrites both methods to use Map.of():

package com.helloworld;

import java.util.Map;

public class Main {
  Map<String, String> createWithNullValue() {
    return Map.of("key", "value", "nullable", null);
  }

  Map<String, String> createWithNullKey() {
    return Map.of(null, "value", "key", "other");
  }
}

Both throw NullPointerException at runtime because Map.of() rejects null keys and values.

What is the full stack trace of any errors you encountered?

java.lang.NullPointerException
    at java.base/java.util.Objects.requireNonNull(Objects.java:220)
    at java.base/java.util.ImmutableCollections$MapN.<init>(ImmutableCollections.java:1437)
    at java.base/java.util.Map.of(Map.java:1384)

Are you interested in contributing a fix to OpenRewrite?

Activity

  1. added a commit that references this issue on May 11, 2026
    972a519
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions