title: How to filter the Map with Stream when null occurs?
body: <p>I want to filter some values in the <code>Map</code> via <code>Stream</code>. Let's see the simple example, where I want to extract entries with keys, for example, higher than 2. </p>
  
  <p>Here is the code I use:</p>
  
  <pre><code>Map&lt;Integer, String&gt; map = new HashMap&lt;&gt;(); 
  map.put(1, "one"); 
  map.put(2, "two"); 
  map.put(3, "three"); 
  map.put(4, "four"); 
  
  Map&lt;Integer, String&gt; map2 = map.entrySet().stream()
      .filter(e -&gt; e.getKey() &gt; 2)
      .collect(Collectors.toMap(e -&gt; e.getKey(), e -&gt; e.getValue()));
  
  System.out.println(map2.toString());
  </code></pre>
  
  <p>The result correct:</p>
  
  <blockquote>
    <p>{3=three, 4=four}</p>
  </blockquote>
  
  <p>When I decide to put the String value as <code>null</code>, that's legal, this is thrown:</p>
  
  <blockquote>
    <p>Exception in thread "main" java.lang.NullPointerException</p>
  </blockquote>
  
  <p>Here is the continuation of the code:</p>
  
  <pre><code>map.put(5, null);
  map.put(6, "six");
  
  Map&lt;Integer, String&gt; map3 = map.entrySet().stream()
      .filter(e -&gt; e.getKey() &gt; 2)
      .collect(Collectors.toMap(e -&gt; e.getKey(), e -&gt; e.getValue()));
  
  System.out.println(map3.toString());
  </code></pre>
  
  <p>I would expect the result:</p>
  
  <blockquote>
    <p>{3=three, 4=four, 5=null, 6=six}</p>
  </blockquote>
  
  <p>Well, it works when I change the condition in the filter's <code>Predicate</code> to <code>e -&gt; e.getKey() &lt; 2</code> since the <code>null</code> value is unaffected. How to handle this with <code>Stream</code>? The <code>null</code> value may occur anywhere intentionally. I don't want to use the for-loop. Shouldn't <code>Stream</code> architecture be more "null-safe"?</p>
  
  <p>The question <a href="https://stackoverflow.com/questions/17081063/how-should-we-manage-jdk8-stream-for-null-values">How should we manage jdk8 stream for null values</a> deals with the different problem. I don't want to use <code>.filter(Objects::nonNull)</code> because I need to keep the <code>null</code> values.</p>
  
  <hr>
  
  <p>Please don't mark it as duplicate with famous <a href="https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it">What is a NullPointerException and how do I fix it</a>. I know this well, I ask the solution using <code>Stream</code>, that is not as low-level as for-loop is. This behaviour quite limits me.</p>