Given the code fragment:

List<Integer> nums = Arrays.asList(10, 20, 8);
System.out.println( 
        //line n1
    );

Which code fragment must be inserted at line n1 to enable the code to print the maximum number in the nums list?

A.

nums.stream().max(Comparator.comparing(a -> a)).get()
B.
nums.stream().max(Integer::max).get()
C.
nums.stream().max()
D.
nums.stream().map(a -> a).max()

題解

串流物件的 max 方法可以取得串流元素中的最大值,需要提供 Comparator 物件作為比較數值大小的依據。

選項 A,使用 Comparator 類別的 comparing 方法來直接指定要使用元素的哪個值來當作比較大小的依據。

選項 B,Comparator 是使用 0 為基準,依靠大於 0、小於 0、等於 0 的判斷來表示兩數的大小。Integer 的 max 方法,會比較傳入的兩個參數,回傳較大的那個,並不是我們要的方法。應該要改成使用 compare 方法才正確,如下:

nums.stream().max(Integer::compare).get()
選項 C,max 方法的用法錯誤。 選項 D,map 方法是用來快速替換元素的內容,而使用「a -> a」替換後的元素就是之前的元素。在這裡若要正確使用 max 方法,可改寫如下:

nums.stream().map(a -> a).max(Integer::compare).get()