有没有办法使用方法引用对降序进行排序?

时间:2015-02-13 01:52:53

标签: java java-8 method-reference

在Java 8中,我可以使用lambda或方法引用进行排序:

List<String> str = Arrays.asList("a","b","A","B");
//Lambda sort ascending
str.sort(s1, s2) -> s1.compareToIgnoreCase(s2);    

//Equivalent sort ascending with method reference 
str.sort(String::compareToIgnoreCase);

//Lambda sort descending 
str.sort(s1, s2) -> s2.compareToIgnoreCase(s1);

//Equivalent sort descending with method reference 
???????? How to do it????

有人知道吗?

1 个答案:

答案 0 :(得分:3)

您可以使用Comparator#reversed

str.sort(((Comparator<String>)String::compareToIgnoreCase).reversed());

或两步

Comparator<String> comp = String::compareToIgnoreCase;
str.sort(comp.reversed());