title: Get key object out of a HashMap in Java
body: <p>I would like to retrieve the original object of a key in a HashMap in Java, what is the best way to do it?</p>
  <p>For example</p>
  <pre><code>HashMap&lt;Integer, Integer&gt; map = new HashMap&lt;Integer, Integer&gt;();
  Integer keyObj = new Integer(10);
  Integer valueObj = new Integer(100);
  
  // And add maybe 1 million other key value pairs here
  //... later in the code, if I want to retrieve the valueObj, given the value of a key to be 10
  Integer retrievedValueObj = map.get(10);
  
  //is there a way to retrieve the original keyObj object with value 10 from map?
  </code></pre>
  <p>Basically, the user can query any value of key here just for the key object, 10 is just an example.
  Some comment say, &quot;you already have the x object, why do you want to get it?&quot;
  Well, this is the same as saying &quot;you already have the value object, why do you want to get it?&quot;
  That is the purpose for the HashMap data structure, store and retrieval.</p>
  <p>Retrieving a value object is easy but it seems no many people know how to retrieve the key object.
  It seems like many people don't get why I want to achieve the object of 10 and ask why? why not just value 10. This is just a greatly simplified model.</p>
  <p>Well, let me give a little bit context. The keyObj is data in another data structure and I need the exact reference of this original key object. Say, there is a linked list of all the key values, and if I want to remove a particular node in the linked list.</p>
  <p>I am not only interested in the value &quot;10&quot;, but also the memory location, i.e. the reference in Java of that &quot;10&quot; object. There could be many &quot;10&quot;'s in memory. But that exact object is what I want to retrieve.</p>
  <p>The iterator approach answer below give an O(n) approach. But what I am looking for is an O(1) retrieval of the key OBJECT given the key value.</p>
  <p>One way I can think of is to store the key object in value as well, like</p>
  <pre><code>class KeyAndValue {
       public Integer key;
       public Integer value;
       public KeyAndValue(Integer key, Integer value) {
           this.key = key;
           this.value = value;
       }
  }
  
  map&lt;Integer, keyAndValueL&gt; map = new map&lt;Integer, keyAndValueL&gt;();
  Integer x = new Integer(10);
  map.add(x, new KeyAndValue(x, 100));
  
  //then I can retrieve the reference of x, given value of key 10
  Integer newKeyObj = map.get(10).key;
  </code></pre>
  <p>but this approach uses more memory and looks like a hack to me. I am wondering if there is a more elegant way in Java.</p>