How to sort an ArrayList?

后端 未结 20 2425
有刺的猬
有刺的猬 2020-11-22 06:19

I have a List of doubles in java and I want to sort ArrayList in descending order.

Input ArrayList is as below:

List testList = new Arr         


        
20条回答
  •  天涯浪人
    2020-11-22 06:58

    Using lambdas (Java8), and stripping it down to the barest of syntax (the JVM will infer plenty in this case), you get:

    Collections.sort(testList, (a, b) -> b.compareTo(a));
    

    A more verbose version:

    // Implement a reverse-order Comparator by lambda function
    Comparator comp = (Double a, Double b) -> {
        return b.compareTo(a);
    };
    
    Collections.sort(testList, comp);
    

    The use of a lambda is possible because the Comparator interface has only a single method to implement, so the VM can infer which method is implementing. Since the types of the params can be inferred, they don't need to be stated (i.e. (a, b) instead of (Double a, Double b). And since the lambda body has only a single line, and the method is expected to return a value, the return is inferred and the braces aren't necessary.

提交回复
热议问题