Which of the following can fill in the blank to print out the numbers 161, 183, and 201 in any order?
class Car { /*from w w w . j a v a 2 s . co m*/ private int speed; public Car(int n) { speed = n; } public int getSpeed() { return speed; } } public class Main { public static void main(String[] args) { Stream<Car> runners = Stream.of(new Car(183), new Car(161), new Car(201)); OptionalInt opt = runners. ; } }
A. map(Car::getSpeed).peek(System.out::println).max() B. mapToInt(Car::getSpeed).peek(System.out::println).max() C. peek(System.out::println).mapToInt(Car::getSpeed).max() D. peek(System.out::println).mapToInt(Car::getSpeed).max() E. None of the above
B.
Options C and D are incorrect because they print the Car object rather than the int value it contains since peek()
is called before mapping the value.
The Car object is something like Car@7d12e123.
Option A is incorrect because the map()
method returns a Stream<Integer>.
While Stream<Integer> does have a max()
method, it requires a Comparator.
By contrast, Option B uses mapToInt()
, which returns an IntStream and does have a max()
method that does not take any parameters.
Option B is the only one that compiles and outputs the int values.