Given the code fragment: List<String> colors = Arrays.asList("red", "green", "yellow"); Predicate<String> test = n - > { System.out.println("Searching""); return n.contains("red"); }; colors.stream() .filter(c -> c.length() > 3) .allMatch(test); What is the result?
Click on the arrows to vote for the correct answer
A. B. C. D.A.
The code creates a List of Strings called colors
with three elements: "red", "green", and "yellow". It also creates a Predicate<String>
called test
which takes a String and returns true if the string contains the substring "red", and prints "Searching..." to the console.
The stream()
method is called on the colors
List, which returns a Stream of Strings. The filter()
method is then called on this Stream with a lambda expression that filters out all Strings with a length less than or equal to 3.
Finally, the allMatch()
method is called on the resulting Stream with the test
Predicate. This method returns true if all elements of the Stream match the given Predicate.
Since the only element in the filtered Stream is "green" which does not contain the substring "red", the test
Predicate will return false for this element. Therefore, the allMatch()
method will return false.
However, before the test
Predicate is applied, it is printed "Searching..." to the console once for each element in the Stream. Therefore, the output of the code will be:
Searching... Searching...
So the correct answer is B.