Java OCA OCP Practice Question 2221

Question

Choose the best option based on this program:

import java.util.regex.Pattern;
import java.util.stream.Stream;

public class Main {
    public static void main(String []args) {
        Stream<String> words = Pattern.compile(" ").splitAsStream("a bb ccc");
        System.out.println(words.map(word -> word.length()).sum());
    }
}
  • A. Compiler error: Cannot find symbol "sum" in interface Stream<Integer>
  • B. this program prints: 3
  • C. this program prints: 5
  • D. this program prints: 6
  • e. this program crashes by throwing java.lang.IllegalStateException


A.

Note

Data and calculation methods such as sum() and average() are not available in the Stream<T> interface;

They are available only in the primitive type versions IntStream, LongStream, and DoubleStream.

To create an IntStream, one solution is to use mapToInt() method instead of map() method in this program.

If mapToInt() were used, this program would compile without errors, and when executed, it will print 6 to the console.




PreviousNext

Related