I have the following class:
import java.util.*;
class ClassA {
public static void main(String...args) {
var list = new ArrayList<String>();
list.add("test");
list.add("abc");
Collections.sort(list, (a, b) -> a.length() >= b.length() ? 1 : 0); // [test, abc]
//Collections.sort(list, (a, b) -> a.compareTo(b)); // [abc, test]
System.out.println(list);
}
}
I thought Collection.sort() would sort accending. I thought a.length() is 4 and b.length() is 3 which would evaluate as (4 >= 3) true. So a.length() >= b.length() ? 1 : 0 would return 1 and mean that "test" is greater than "abc". So it should be sorted like [abc, test].
But I only get the result [abc, test] when I change the code to a.length() >= b.length() ? 1 : -1, which seems to indicate that a.length() >= b.length()evaluates as false. Why is that?
Why does the first lambda expression lead to [test, abc], while the modified version leads to [abc, test]?
Collections.sort(list, (a, b) -> a.compareTo(b)); works like expected.