×

java · level 3 · unit 4 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Chain steps on an Optional and open it once, at the end.

An Optional has its own map and filter. map changes the value if there is one and does nothing if not. filter empties the box when the value fails a test. You can chain them without a single if.

Streams hand you Optional values too. gives the first item and max(comparator) the biggest, because an empty stream has neither. Finish with orElse, with when the fallback is costly to make, or with when a missing value is a real error.

get() also opens the box, but it throws when the box is empty. Avoid it: the other methods say clearly what should happen.

import java.util.Comparator;
import java.util.List;
public class Main {
    public static void main(String[] args) {
        List<String> users = List.of("amir:amir@mail.com", "bo:", "cat:cat@web.net");
        String email = users.stream()
            .filter(user -> user.startsWith("bo:"))
            .findFirst()
            .map(user -> user.substring(user.indexOf(":") + 1))
            .filter(address -> address.contains("@"))
            .orElse("no email on file");
        System.out.println(email);
        String longest = users.stream()
            .max(Comparator.comparing(String::length))
            .orElseThrow();
        System.out.println(longest);
    }
}

orElseThrow() with no arguments throws NoSuchElementException when the box is empty.