LearnFrenzy
Sign in Take a free test

Lambda Expressions · Predict the Output · Question 17

Lambdas with Optional Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 17 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.Optional;

public class Main {
    static Optional<String> find(String key) { return key.startsWith("u") ? Optional.of(key.substring(1)) : Optional.empty(); }

    public static void main(String[] args) {
        String a = find("u42").map(Integer::parseInt).map(n -> n * 2).map(String::valueOf).orElse("none");
        String b = find("x9").map(String::toUpperCase).orElseGet(() -> "fallback");
        StringBuilder sb = new StringBuilder();
        find("uok").ifPresentOrElse(v -> sb.append("got ").append(v), () -> sb.append("missing"));
        System.out.println(a + " " + b + " " + sb + " " + find("u").filter(s -> !s.isEmpty()).isPresent());
    }
}
  • A 84 fallback got ok false Correct
  • B 84 X9 got ok false
  • C 42 fallback got ok true
  • D u84 fallback got ok false
Correct Answer: Option A

Each map applies only if a value is present. find("u") gives Optional.of(""), which the filter removes.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links