title: Java stream find value by key if exists
body: <p>I'm having simple DataStructure</p>
  
  <pre><code>public class DataStructure {
      private String key;
      private String value;
      //get, set
  }
  </code></pre>
  
  <p>And I need to return value from `List' based on key and I want to do it Java8 way, with streams. I think code speaks for himself: </p>
  
  <pre><code>public class Main {
      public static void main(String args[]) {
        List&lt;DataStructure&gt; dataList = new ArrayList&lt;&gt;();
        dataList.add(new DataStructure("first", "123"));
        dataList.add(new DataStructure("second", "456"));
  
          System.out.println(findValueOldSchool(dataList, "third")); //works ok
          System.out.println(findValueStream(dataList, "third")); //throws NoSuchElementException
      }
  
      static String findValueOldSchool(List&lt;DataStructure&gt; list, String key) {
          for (DataStructure ds : list) {
              if (key.equals(ds.getKey())) {
                  return ds.getValue();
              }
          }
          return null;
      }
  
      static String findValueStream(List&lt;DataStructure&gt; list, String key) {
          return list.stream()
                  .filter(ds -&gt; key.equals(ds.getKey()))
                  .findFirst()
                  .get().getValue();
      }
  }
  </code></pre>
  
  <p>How can I modify <code>findValueStream()</code> to not throw NoSuchValueException while I search for non existing key? I don't want to return <code>Optional&lt;String&gt;</code> because this method is already used in a lot of places in project. And, ofcourse I'v tried <code>map</code>, <code>ifPresent</code>, <code>anyMatch</code>, just can't find the right way to do it. </p>