Advertisement
miguelmartins1987

Java - avoiding null entries in map

May 26th, 2022
868
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.05 KB | None | 0 0
  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.Optional;
  4.  
  5. public class MyClass {
  6.     public static void main(String args[]) {
  7.       Map<String, Optional<String>> myMap = new HashMap<>();
  8.       myMap.put("this exists", Optional.of("abc"));
  9.       myMap.put("this also exists", Optional.of("def"));
  10.       myMap.put("this does not exist", Optional.empty());
  11.  
  12.       System.out.println(myMap);
  13.      
  14.       Optional<String> existing = myMap.get("this exists");
  15.       if (existing.isPresent()) {
  16.           System.out.println(existing.get());
  17.       }
  18.       else {
  19.           System.out.println("Does not exist!");
  20.       }
  21.      
  22.       Optional<String> nonExisting = myMap.get("this does not exist");
  23.       if (nonExisting.isPresent()) {
  24.           System.out.println(nonExisting.get());
  25.       }
  26.       else {
  27.           System.out.println("Does not exist!");
  28.       }
  29.      
  30.       Optional<String> shouldBeNull = myMap.get("no such entry");
  31.       if (shouldBeNull == null) {
  32.           System.out.println("It is null!");
  33.       }
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement