title: Java 8 extract first key from matching value in a Map
body: <p>Suppose I have a map of given name, surname pairs and I want to find the given name of the first entry in that map that has the surname matching a certain value.
  How would we do this in a java 8 fashion.</p>
  
  <p>In my test case example below I put two ways that would do it.</p>
  
  <p>However the first one (looking for the given name of the first person with a surname of "Donkey") will throw java.util.NoSuchElementException: No value present so it is not safe.</p>
  
  <p>The second one works but it is not only harder to read but it it is a bit not quite functional.</p>
  
  <p>Just wondering if someone here would suggest me an easier clearer way of achieving this using either <code>stream()</code> or <code>forEach()</code> or both.</p>
  
  <pre><code>@Test
  public void shouldBeAbleToReturnTheKeyOfTheFirstMatchingValue() throws Exception {
      Map&lt;String, String&gt; names = new LinkedHashMap&lt;&gt;();
      names.put("John", "Doe");
      names.put("Fred", "Flintstone");
      names.put("Jane", "Doe");
      String keyOfTheFirst = names.entrySet().stream().filter(e -&gt; e.getValue().equals("Doe")).findFirst().get().getKey();
      assertEquals("John", keyOfTheFirst);
  
      try {
          names.entrySet().stream().filter(e -&gt; e.getValue().equals("Donkey")).findFirst().get();
      } catch (NoSuchElementException e){
          // Expected
      }
  
      Optional&lt;Map.Entry&lt;String, String&gt;&gt; optionalEntry = names.entrySet().stream().filter(e -&gt; e.getValue().equals("Donkey")).findFirst();
      keyOfTheFirst = optionalEntry.isPresent() ? optionalEntry.get().getKey() : null;
  
      assertNull(keyOfTheFirst);
  }
  </code></pre>
  
  <p>Thank you in advance.</p>