title: Is there any way how to get the key (or the whole entry) from a `Map`?
body: <p>Is there any way how to get the key (or the whole entry) from a <code>HashMap</code> (or another suitable <code>Map</code>) <strong>efficiently</strong>?</p>
  
  <p>Before somebody says, I never need it: I do. I have a loop like this</p>
  
  <pre><code>for (long i=0; i&lt;1e12; ++i) {
      Key key = new Key(i);
      Value value = map.get(key);
      if (something(key, value)) list.add(key);
  }
  </code></pre>
  
  <p>and my <code>key</code> needlessly takes memory which could be saved if I could replace <code>list.add(key)</code> by something like  <code>list.add(map.getKey(key))</code> (the new instance would be eligible for GC). <strong>While they're equal, reusing the old instance would save memory.</strong></p>
  
  <p>I know I can embed the key into the value or use Guava's <code>Interner</code>; both helps, but both also costs some memory.</p>
  
  <hr>
  
  <p>To address some misunderstanding comments: If efficiency was no issue, the following would do</p>
  
  <pre><code>Key getKeyFromMap(Key key, Map&lt;Key, ?&gt; map) {
      for (Key key2 : map.keySet()) {
          if (key.equals(key2)) return key2;
      }
      return null;
  }
  </code></pre>
  
  <hr>
  
  <p>The most efficient solution as described in the accepted answer:</p>
  
  <pre><code>public static &lt;K, V&gt; K getKey(K key, HashMap&lt;K, V&gt; map) {
      final Entry&lt;K, V&gt; entry = map.getEntry(key);
      return entry==null ? null : entry.getKey();
  }
  </code></pre>
  
  <p>The problem is that it must be placed into <code>package java.util</code> as it uses a package private method. It can be dangerous to use such a method, but it's no problem in my "run-once" use case.</p>