title: How to create a hashmap that contains optional and when retreiving it gives me the value or Optional.empty but there are restrictions
body: <blockquote>
  <p>How to create a hashmap that contains optional and when retreiving it gives me the value or Optional.empty? However, I am not allowed to check for null, Optional.empty() or use <code>isPresent()</code>, <code>isEmpty()</code>, <code>get()</code>.</p>
  </blockquote>
  <p>For <code>Optional&lt;V&gt; get</code>, <code>.get()</code> would either give me null or Optional value but what I want is <code>Optional.empty()</code> or Optional value as I would need to chain these optional together later.</p>
  <p>For example, <code>.get(&quot;John&quot;).flatMap(x -&gt; x.get(&quot;ModName&quot;)).flatMap(x -&gt; x.get(&quot;TestName&quot;)).map(Assessment::getGrade)</code>.
  If &quot;John&quot; does not exist in the first map then <code>.get(&quot;John&quot;)</code> will give me a null and if I use <code>.flatMap(x -&gt; x.get(&quot;ModName&quot;))</code>, I would get a null pointer exception.</p>
  <pre class="lang-java prettyprint-override"><code>import java.util.HashMap;
  import java.util.Map;
  import java.util.Optional;
  
  class CustomMap&lt;V&gt; {
      private final Map&lt;String, Optional&lt;V&gt;&gt; map;
  
      public CustomMap() {
          map = new HashMap&lt;String, Optional&lt;V&gt;&gt;();
      }
  
      public Optional&lt;V&gt; get(String key) {
          return map.get(key);
      }
  
      public int size() {
          return map.size();
      }
  
      public CustomMap&lt;V&gt; put(V item) {
          map.put(item.getKey(), Optional.ofNullable(item));
          return this;
      }
  </code></pre>