title: Java: generic filter map function
body: <p>I'm trying to develop a generic function to filter maps.</p>
  
  <p>The code I have so far is:</p>
  
  <pre><code>public static Map&lt;?, ?&gt; filterAttrs(Map&lt;?, ?&gt; args, String... unless) {
  
      Map&lt;?, ?&gt; filteredAttrs = Map.class.newInstance();
  
      Arrays.sort(unless);
      for (Object o : args.keySet()) {
          if (Arrays.binarySearch(unless, o.toString()) &lt; 0 ) {
              filteredAttrs.put(o, args.get(o));
          }
      }
      return filteredAttrs;
  }
  </code></pre>
  
  <p>I get the following errors in filteredAttrs.put</p>
  
  <blockquote>
    <p>The method put(capture#5-of ?, capture#6-of ?) in the type Map is not applicable for the arguments (Object, capture#8-of ?)</p>
  </blockquote>
  
  <p>I don't know how to instantiate a generic <code>Map</code> (I tried with 1Map.class.newInstance()`).</p>
  
  <p>Any ideas?</p>
  
  <p>Edit: after reading many answers, the problem seems to be how to make <code>filteredAttrs</code> be an instance of the same type as <code>args</code>. <code>(Map) args.getClass().newInstance()</code> seems to do the trick.</p>