Given the code fragment:

Stream<List<String>> iStr = Stream.of(
        Arrays.asList("1", "John"),
        Arrays.asList("2", null));
IntStream nInSt = iStr.flatMapToInt((x) -> x.stream());
nInSt.forEach(System.out::print);

What is the result?

A.

1John2null

B.

12

C. A NullPointerException is thrown at run time.
D. A compilation error occurs.

题解

iStr 所参考到的串流对象中的元素为字符串型态的 List 对象,其 stream 方法产生的 Stream<String> 对象无法直接作为 IntStream 对象。若修改成以下程序,可以成功编译:

IntStream nInSt = iStr.flatMapToInt((x) -> x.stream().mapToInt(Integer::valueOf));

以上程序虽然可以成功编译,但运行时会抛出 NumberFormatException,因为「John」字符串不能转成整数。

如果要能成功运行,不应使用 flatMapToInt 方法,应改写程序如下:

IntStream nInSt = iStr.mapToInt((x) -> Integer.parseInt(x.get(0)));

改写之后程序会输出:

12