How to sort an ArrayList?

后端 未结 20 2057
有刺的猬
有刺的猬 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<Double> 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.

    0 讨论(0)
  • 2020-11-22 07:01

    You can use Collections.sort(list) to sort list if your list contains Comparable elements. Otherwise I would recommend you to implement that interface like here:

    public class Circle implements Comparable<Circle> {}
    

    and of course provide your own realization of compareTo method like here:

    @Override
        public int compareTo(Circle another) {
            if (this.getD()<another.getD()){
                return -1;
            }else{
                return 1;
            }
        }
    

    And then you can again use Colection.sort(list) as now list contains objects of Comparable type and can be sorted. Order depends on compareTo method. Check this https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html for more detailed information.

    0 讨论(0)
提交回复
热议问题