nerdexam
Oracle

1Z0-819 · Question #76

Given: public class FunctionalInterfaceTest { public static void main(String[] args) { List<String> fruits = Arrays.asList("apple", "orange", "banana"); Consumer<String> c = System.out::print…

The correct answer is E. apple:APPLE orange:ORANGE banana:BANANA. Option E is correct because Consumer.andThen() chains two consumers that each receive the same input value s. For each fruit, c (bound to System.out::print) outputs the lowercase string without a newline, then the lambda immediately outputs ":" + s.toUpperCase() with println…

Working with Streams and Lambda Expressions

Question

Given: public class FunctionalInterfaceTest { public static void main(String[] args) { List<String> fruits = Arrays.asList("apple", "orange", "banana"); Consumer<String> c = System.out::print; Consumer<String> output = c.andThen(s -> System.out.println(":" + s.toUpperCase ())); fruits.forEach(output); } } What is the output?

Options

  • AAPPLE:APPLE ORANGE:ORANGE BANANA:BANANA
  • Bapple:APPLE orange:ORANGE banana:BANANA
  • Capple:APPLE orange:ORANGE banana:BANANA ban na
  • Dapple orange banana APPLE ORANGE BANANA
  • Eapple:APPLE orange:ORANGE banana:BANANA

How the community answered

(27 responses)
  • B
    7% (2)
  • C
    4% (1)
  • D
    15% (4)
  • E
    74% (20)

Explanation

Option E is correct because Consumer.andThen() chains two consumers that each receive the same input value s. For each fruit, c (bound to System.out::print) outputs the lowercase string without a newline, then the lambda immediately outputs ":" + s.toUpperCase() with println, producing one complete line like apple:APPLE per fruit - three lines total.

Why the distractors fail:

  • A is wrong because System.out::print preserves the original case - the fruits are lowercase, so the left side of : cannot be APPLE.
  • B appears similar but shows all output on a single line with spaces; println in the lambda adds a newline after each entry, so each pair appears on its own line.
  • C introduces a nonsensical ban na fragment - no part of the code produces split or partial tokens.
  • D suggests the two consumers print separately on their own lines (lowercase, then uppercase); that would only happen if they were called independently, not chained where both receive the same s in the same invocation.

Memory tip: Think of andThen as "same input, sequential side effects" - both consumers see the original value, so the lambda's s.toUpperCase() is always derived from the untouched input, not from whatever the first consumer printed.

Topics

#Consumer functional interface#method references#andThen chaining#forEach iteration

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice