LearnFrenzy
Sign in Take a free test

Lambda Expressions · Predict the Output · Question 2

Chaining plus3 and times2 in both orders Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        Function<Integer, Integer> plus3 = x -> x + 3;
        Function<Integer, Integer> times2 = x -> x * 2;
        System.out.println(plus3.andThen(times2).apply(5) + " " + plus3.compose(times2).apply(5) + " " + times2.andThen(times2).andThen(plus3).apply(1));
    }
}
  • A 16 13 7 Correct
  • B 13 16 7
  • C 16 16 7
  • D 13 13 5
Correct Answer: Option A

andThen: (5 + 3) × 2 = 16. compose: 5 × 2 + 3 = 13. Chain: 1 → 2 → 4 → 7.

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