Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8266237

Unexpected NullPointerException from Stream.collect(Collectors.toMap)

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Open
    • Priority: P3
    • Resolution: Unresolved
    • Affects Version/s: 17
    • Fix Version/s: None
    • Component/s: core-libs
    • Labels:
      None

      Description

      $ cat CollectToMap.java
      import java.util.Collections;
      import java.util.stream.Collectors;

      public class CollectToMap {

          public static void main(String[] args) {
              Collections.singleton(null)
                         .stream()
                         .collect(Collectors.toMap(k -> new Object(), v -> null));
          }
      }
      $ javac CollectToMap.java
      $ java CollectToMap
      Exception in thread "main" java.lang.NullPointerException
              at java.base/java.util.Objects.requireNonNull(Objects.java:208)
              at java.base/java.util.stream.Collectors.lambda$uniqKeysMapAccumulator$1(Collectors.java:180)
              at java.base/java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
              at java.base/java.util.Collections$2.tryAdvance(Collections.java:4820)
              at java.base/java.util.Collections$2.forEachRemaining(Collections.java:4828)
              at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
              at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
              at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
              at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
              at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682)
              at CollectToMap.main(CollectToMap.java:9)

      ----------------------
      This is unexpected because neither Stream.collect nor Collectors.toMap mentions this. This is also surprising as null key is okay:

      $ cat CollectToMap.java
      import java.util.Collections;
      import java.util.stream.Collectors;

      public class CollectToMap {

          public static void main(String[] args) {
              Collections.singleton(null)
                         .stream()
                         .collect(Collectors.toMap(k -> null, v -> new Object()));
          }
      }
      $ javac CollectToMap.java
      $ java CollectToMap
      $


        Attachments

          Issue Links

            Activity

              People

              Assignee:
              smarks Stuart Marks
              Reporter:
              prappo Pavel Rappo
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated: