title: How to Filter a Map to retain only specific keys in Java
body: <p>I have been using <code>map.keySet().retainAll(&lt;set of keys&gt;)</code> for this purpose , but just came across a scenario where this is not working as expected.</p>
  
  <p>See the sample code below. I am expecting <code>object1</code> map to be returned with keys (key1 and key2) after filter, but this gives me blank output. Note: if I uncomment the line that adds key3 to <code>object1</code> , it is working fine (returning map with key1 and key2). Why? How to fix this issue? Is there any alternative approach?</p>
  
  <pre><code>public class Demo {
  
      public static void main(String args[]){
  
          Map&lt;String,Object&gt; object1 = new HashMap&lt;&gt;();
          object1.put("key1","One");
          object1.put("key2","Two");
          //object1.put("key3","Three");
  
          List&lt;Map&lt;String,Object&gt;&gt; objects = new ArrayList&lt;&gt;();
          objects.add(object1);
  
  
          Set&lt;String&gt; attributes = new HashSet&lt;&gt;();
             attributes.add("key1");
             attributes.add("key2");
  
          System.out.println("Objects before filter:"+objects);
  
          System.out.println("Objects after filter:"+objects.stream().filter(map -&gt; map.keySet().retainAll(attributes)).collect(Collectors.toList()));
  
      }
  
  }
  </code></pre>