Java OCA OCP Practice Question 2781

Question

What is the simplest way of rewriting this code?

List<Integer> l = IntStream.range(1, 6) 
   .mapToObj(i -> i).collect(Collectors.toList()); 
l.forEach(System.out::println); 
A.   IntStream.range(1, 6); 
B.   IntStream.range(1, 6).forEach(System.out::println); 
C.   IntStream.range(1, 6) 
     .mapToObj(1 -> i) 
     .forEach(System.out::println); 
D.   None of the above is equivalent. 
E.   The provided code does not compile. 


B.

Note

Both lists and streams have forEach() methods.

There is no reason to collect into a list just to loop through it.




PreviousNext

Related