0

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

2
  • 1
    The first parameter of Arrays.sort must be an array, you passed a List. Commented Feb 7, 2022 at 21:11
  • you cant use utility class Arrays with collections. Probably you need this insteadCollections.sort(strs, (a, b) -> b.compareTo(a)); Commented Feb 7, 2022 at 21:15

2 Answers 2

0

As duncg mentioned just do:

Object[] array = strs.toArray();
Arrays.sort(array, (a, b) ->  ((String) b).compareTo((String)a) );
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.