Nicky :
I am trying to sort list of string through my own comparator. I saw the below template for list of developers.
//lambda
listDevs.sort((Developer o1, Developer o2)->o1.getAge()-o2.getAge());
My code: (this is giving me compile error)
List<String> s = new ArrayList<>();
Collections.sort(s, (String a, String b)-> {
return a.length() > b.length()
});
This code is not compiling. Can someone help me what is wrong with what I am doing?
Deadpool :
Arrays.sort
is used for sorting Arrays
not for Collection
objects, use Collections.sort to sort ArrayList
Collections.sort(s,(a,b)->a.length()-b.length());
And corresponding lambda expression is wrong (String a,String b)-> a.length() > b.length()
which returns Boolean value. Where Comparator.compare should return int
value. And also the type of the parameters can be explicitly declared or it can be inferred from the context.
int compare(T o1, T o2)
You can also use List.sort
s.sort((a,b)->a.length()-b.length());