Skip to main content

Command Palette

Search for a command to run...

sort array in descending order using Comparator

Published
1 min read
S

I love learning about technology and sharing that with others

  1. sort in descending order -> n2.compareTo(n1)
import java.util.Arrays;
import java.util.Comparator;


// program to sort the array in reverse oder using Comparator 
public class Test {

    public static void main(String args[]) {


        Comparator<Integer> numberComparator = (n1,n2) -> n2.compareTo(n1);
        //internally compareTo -> will call compare 
        //for compare -> x<y --> -1
        // y is the new value 

        Integer arr[]={1,4,3,2};

        Arrays.sort(arr,numberComparator);

        for(Integer n: arr) {
            System.out.println(n);
        }


    }


}
  1. Sort in Ascending order -> n1.compareTo(n2)

More from this blog

H

hashcodehub

271 posts

Consistent, Passionate and Organized :)