close
一. 題目
Given the code fragment:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Stream<List<String>> iStr = Stream.of( | |
Arrays.asList("1", "John"), | |
Arrays.asList("2", null)); | |
Stream<String> nInSt = iStr.flatMapToInt((x) -> x.stream()); | |
nInSt.forEach(System.out::print); |
A. 1John2null
B. 12
C. A NullPointerException is thrown at run time.
D. A compilation error occurs.
二. 答案
D
三. 解析
iStr是泛型為List<String>的 Stream流。
若使用 flatMapToInt(),return IntStream,無法使用 Stream<T>去操縱
改變承接變數的型態改成 IntStream
這個時候 x.stream(),把 iStr的每個元素變成 Stream<String>,與回傳型態 IntStream不相符,會出現型態轉換錯誤。
只要在 x.stream後面加上.mapToInt(Integer::valueOf),即可編譯成功。
但執行程式時,因為 iStr含有非數字的值 "John",
所以發生錯誤 Exception in thread "main" java.lang.NumberFormatException: For input string: "John"
文章標籤
全站熱搜