java · level 3 · unit 4 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
orElse or orElseGet? Guess first.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.Optional;
public class Main {
static String loadDefault() {
System.out.println("loading default...");
return "light";
}
public static void main(String[] args) {
Optional<String> theme = Optional.of("dark");
System.out.println(theme.orElse(loadDefault()));
System.out.println(theme.orElseGet(() -> loadDefault()));
}
}
your turn
Your turn. Find a free room.
On line 6, keep only the rooms that end with :free. endsWith checks the end of a string.
output
press run to see what happens
fix it
The auction crashes before the first bid. Can you fix it?
output
press run to see what happens
- Line 9 throws
NoSuchElementException. How many bids are there so far? - With no bids,
maxhands back an emptyOptional, andgethas nothing to give. - Change
.get()to.orElse(0)on line 9, then run.
nailed it
you can chain through maybe-missing values. :D
mapandfilterwork inside anOptional, skipping when empty.findFirstandmaxhand back anOptional.- Open it with
orElse,orElseGetororElseThrow, notget.
new words in your collection
- orElseGet
- orElseThrow
- findFirst
This lesson isn’t saved. A free account remembers every lesson you finish.