Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Optional;
- public class MyClass {
- public static void main(String args[]) {
- Map<String, Optional<String>> myMap = new HashMap<>();
- myMap.put("this exists", Optional.of("abc"));
- myMap.put("this also exists", Optional.of("def"));
- myMap.put("this does not exist", Optional.empty());
- System.out.println(myMap);
- Optional<String> existing = myMap.get("this exists");
- if (existing.isPresent()) {
- System.out.println(existing.get());
- }
- else {
- System.out.println("Does not exist!");
- }
- Optional<String> nonExisting = myMap.get("this does not exist");
- if (nonExisting.isPresent()) {
- System.out.println(nonExisting.get());
- }
- else {
- System.out.println("Does not exist!");
- }
- Optional<String> shouldBeNull = myMap.get("no such entry");
- if (shouldBeNull == null) {
- System.out.println("It is null!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement