AI Hints
Home›Java Tutorial›Optional, var and Pattern Matching
Java · Lesson 106 of 120

Optional

Maybe a value.

⏱ 2 min read▶ Video at 2:15:18🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Null causes many crashes. Optional is a small box that either holds a value, or is empty. It makes it clear that a value might be missing, and forces you to think about it.

  • null causes crashes
  • A box: value or empty
  • Missing is clear

Optional in action

Find user returns an Optional. Optional dot of holds a value, and Optional dot empty holds nothing. Is present checks if there's a value. Or else gives a fallback, when it's empty. Map changes the value, only if there is one. And if present runs code only when there's a value. Run it. True, false. Ana, then guest. Ana in capitals. And found ana prints only once.

Main.javajava
import java.util.*;
public class Main {
    static Optional<String> findUser(int id) {
        if (id == 1) return Optional.of("ana");
        return Optional.empty();
    }

    public static void main(String[] args) {
        Optional<String> a = findUser(1);
        Optional<String> b = findUser(7);
        System.out.println(a.isPresent() + " " + b.isPresent());
        System.out.println(a.get());
        System.out.println(b.orElse("guest"));
        System.out.println(a.map(String::toUpperCase).orElse("?"));
        b.ifPresent(name -> System.out.println("Found " + name));
        a.ifPresent(name -> System.out.println("Found " + name));
    }
}
Output
true false
ana
guest
ANA
Found ana

Optional from streams

Stream steps like find first, and max, return an Optional, because there might be no answer. Here, find first finds a price over thirty, but nothing is over a hundred. Run it. Forty, and zero as the fallback. The max is forty.

Main.javajava
import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<Integer> prices = List.of(12, 40, 7, 25);
        Optional<Integer> firstBig = prices.stream().filter(p -> p > 30).findFirst();
        Optional<Integer> huge = prices.stream().filter(p -> p > 100).findFirst();
        System.out.println(firstBig.orElse(0) + " " + huge.orElse(0));
        System.out.println(prices.stream().max(Integer::compare).get());
    }
}
Output
40 0
40

Optional tips

Use Optional as a return type, when a result might be missing. Prefer or else, map, and if present, over get. Get throws an exception if the box is empty. And never put null inside an Optional.

keyvalue
Return typeOptional<User>
FallbackorElse(x)
Transformmap(…)
Avoidget() on empty

Summary

Optional is a box that holds a value, or nothing. Use or else, map, and if present to handle both cases safely. Next, var.

Key takeaways
  • Optional.of / empty
  • orElse
  • ifPresent
Next up: var — let Java work out the type