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?
Click on the arrows to vote for the correct answer
A. B. C. D.A.
This code fragment creates a List of Integer objects using the Arrays.asList() method and assigns it to the reference variable "nums". Then it prints out the maximum number in the "nums" list. However, the code fragment doesn't have any statement to find the maximum number in the list. We need to add code at line n1 that finds the maximum number in the "nums" list and prints it.
Option A: nums.stream().max(Comparator.comparing(a -> a)).get() This option creates a stream of the "nums" list, applies the max() method to find the maximum element, and returns it. The comparing() method of Comparator is used to compare Integer objects. This option is correct, and it should print the maximum number in the "nums" list.
Option B: nums.stream().max(Integer::max).get() This option creates a stream of the "nums" list, applies the max() method to find the maximum element, and returns it. The max() method of Integer is used as the comparator. This option is incorrect because the max() method of Integer takes two integer arguments and returns the larger of the two. It doesn't compare Integer objects.
Option C: nums.stream().max() This option creates a stream of the "nums" list, applies the max() method to find the maximum element, and returns it. This option is correct, and it should print the maximum number in the "nums" list.
Option D: nums.stream().map(a -> a).max() This option creates a stream of the "nums" list, applies the map() method to transform each element into itself (which is a no-op), applies the max() method to find the maximum element, and returns it. This option is correct, and it should print the maximum number in the "nums" list.
Therefore, options A, C, and D are correct, but option B is incorrect. So, the answer is A, C, or D.