Java OCA OCP Practice Question 2759

Question

We have a method that returns a sorted list without changing the original.

Which of the following can replace the method implementation to do the same with streams?.

private static List<String> sort(List<String> list) { 
   List<String> copy = new ArrayList<>(list); 
   Collections.sort(copy, (a, b) -> b.compareTo(a)); 
   return copy; 
} 
A.   return list.stream() 
     .compare((a, b) -> b.compareTo(a)) 
     .collect(Collectors.toList()); 

B.   return list.stream() 
     .compare((a, b) -> b.compareTo(a)) 
     .sort(); //www  . j av  a2s  .c  om

C.   return list.stream() 
     .compareTo((a, b) -> b.compareTo(a)) 
     .collect(Collectors.toList()); 

D.   return list.stream() 
     .compareTo((a, b) -> b.compareTo(a)) 
     .sort(); 

E.   return list.stream() 
     .sorted((a, b) -> b.compareTo(a)) 
     .collect(); 

F.   return list.stream() 
     .sorted((a, b) -> b.compareTo(a)) 
     .collect(Collectors.toList()); 


F.

Note

The sorted() method is used in a stream pipeline to return a sorted Stream.

A collector is needed to turn the stream back into a List.

The collect() method takes the desired collector.




PreviousNext

Related