Java sort arrays in descending order.

import java.util.Arrays;
import java.util.Comparator;

public class App {

    public static void main(String[] args) {
        Integer[] nums = {1, 3, 2, 4, 5};

        // method 1: anonymous class
        Arrays.sort(nums, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        });

        // method 2: lambda
        Arrays.sort(nums, (a, b) -> b - a);
        Arrays.sort(nums, (a, b) -> b.compareTo(a));

        // method 3: convenient Comparator default method
        Arrays.sort(nums, Comparator.reverseOrder());

        System.out.println(Arrays.toString(nums));
    }
}
TOPâ–˛
Post tagged with: java