GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — Optional — java.evolved

Home / Topics / Optional
🏷 Optional 4 patterns

Topic: Optional

All Java patterns related to Optional — java.evolved

Streams

Optional.ifPresentOrElse()

Old Optional<User> user = findUser(id); if (user.isPresent()) { greet(user.get()); } else { handleMissing(); }
Modern findUser(id).ifPresentOrElse( this::greet, this::handleMissing );
hover to see modern →
JDK 9+ learn more →
Streams

Optional.or() fallback

Old Optional<Config> cfg = primary(); if (!cfg.isPresent()) { cfg = secondary(); } if (!cfg.isPresent()) { cfg = defaults(); }
Modern Optional<Config> cfg = primary() .or(this::secondary) .or(this::defaults);
hover to see modern →
JDK 9+ learn more →
Errors

Optional chaining

Old String city = null; if (user != null) { Address addr = user.getAddress(); if (addr != null) { city = addr.getCity(); } } if (city == null) city = "Unknown";
Modern String city = Optional.ofNullable(user) .map(User::address) .map(Address::city) .orElse("Unknown");
hover to see modern →
JDK 9+ learn more →
Errors

Optional.orElseThrow() without supplier

Old // Risky: get() throws if empty, no clear intent String value = optional.get(); // Verbose: supplier just for NoSuchElementException String value = optional .orElseThrow(NoSuchElementException::new);
Modern // Clear intent: throws NoSuchElementException if empty String value = optional.orElseThrow();
hover to see modern →
JDK 10+ learn more →
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.