Java OCA OCP Practice Question 2219

Question

Choose the best option based on this program:

import java.util.*;

public class Main {
    public static void main(String []args) {
        List<String> strings = Arrays.asList("A ", "B", "C", "D");
        Collections.sort(strings, (str1, str2) -> str2.compareTo(str1));
        strings.forEach(string -> System.out.print(string));
    }
}
A.  Compiler error: improper lambda function definition
B.  this program prints: ABCD
C.  this program prints: DCBA
D.  this program will compile fine, and when run, will 
    crash by throwing a runtime exception.


C.

Note

this is a proper definition of a lambda expression.

Since the second argument of Collections.sort() method takes the functional interface Comparator and a matching lambda expression is passed in this code.

The second argument is compared with the first argument in the lambda expression(str1, str2) -> str2.compareTo(str1).

The comparison is performed in descending order.




PreviousNext

Related