Given the code fragment:



List<String> nL = Arrays.asList("Jim", "John", "Jeff");
Function<String, String> funVal = s -> "Hello : ".concat(s);
nL.stream()
        .map(funVal)
        .peek(System.out::print);

What is the result?

A.

Hello : JimHello : JohnHello : Jeff

B.

JimJohnJeff

C. The program prints nothing.
D. A compilation error occurs.

題解

這個題目提供的程式碼並不會輸出任何東西,若將第22行開始的程式修改如下:

List<String> nL = Arrays.asList("Jim", "John", "Jeff");
Function<String, String> funVal = s -> "Hello : ".concat(s);
nL.stream()
        .map(funVal)
        .forEach(System.out::print);

或:

nL.stream()
        .map(funVal)
        .peek(System.out::print)
        .count();

才會輸出:

Hello : JimHello : JohnHello : Jeff