Home > front end >  java lambda expression in sorting. diff between .sort() and Arrays.sort()
java lambda expression in sorting. diff between .sort() and Arrays.sort()

Time:02-08

Please see the code below, on the fourth line, put the lambda expression in the .sort() method, it works fine.

The fifth line, using Arrays.sort() will report an error. I would like to know where is the difference between the two. and how to properly use lambda expressions in Arrays.sort()

    var strs = new ArrayList<String>();
    strs.add("AA");
    strs.add("BB");
    strs.sort((a,b) -> b.compareTo(a)); // OK
    // Arrays.sort(strs, (a, b) ->  b.compareTo(a) ); // CAN NOT COMPILE java: no suitable method found for sort...

Related questions: using Arrays.sort with Lambda

CodePudding user response:

As duncg mentioned just do:

Object[] array = strs.toArray();
Arrays.sort(array, (a, b) ->  ((String) b).compareTo((String)a) );

CodePudding user response:

Arrays and lists are different so you can't pass an instance of one to a method expecting the other. But the List interface has a sort() method that takes a Comparator. To sort a list, try it like this. Strings implement the Comparable interface and their natural order is ascending. So just specify a reverse order Comparator for comparing.

var strs = new ArrayList<String>();
   strs.add("AA");
   strs.add("BB");

strs.sort(Comparator.reverseOrder());

strs.forEach(System.out::println);

prints

BB
AA
  •  Tags:  
  • Related