1Z0-809: Java SE 8 Programmer II Exam - Question Answer

Java Stream API - Code Fragment Analysis

Question

Given the code fragment: List<String> str = Arrays.asList ("my", "pen", "is", "your', "pen"); Predicate<String> test = s -> { int i = 0; boolean result = s.contains ("pen"); System.out.print(i++) + ":"); return result; }; str.stream() .filter(test) .findFirst() .ifPresent(System.out ::print); What is the result?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D. E.

A.

The code creates a list of strings str containing the values "my", "pen", "is", "your", and "pen". It then creates a Predicate named test that checks if a given string contains the substring "pen".

In the test Predicate, there is a local variable i initialized to 0. Whenever the test Predicate is called, it will print the value of i followed by a colon (":"). After printing the value of i, i is incremented by 1. The test Predicate returns true if the input string contains "pen", and false otherwise.

The str list is converted to a stream and filtered using the test Predicate. The findFirst() method returns an Optional containing the first element of the filtered stream. If the Optional is not empty, the ifPresent() method prints the value of the element using System.out.print().

The output of the program will be: 0:pen

Here's a step-by-step explanation of how the output is produced:

  • The stream is filtered using the test Predicate.
  • The first string that matches the test Predicate is "pen".
  • The test Predicate is called once for this string, which prints "0:" (the value of i is 0 at this point) and returns true.
  • The findFirst() method returns an Optional containing "pen".
  • The ifPresent() method calls System.out.print() with the value "pen", producing the output "pen".
  • Since the test Predicate was called once and printed "0:", the final output is "0:pen".