让我们首先创建一个字符串列表:
List<String> list = Arrays.asList("Tom", "Jack", "Ryan", "Kevin", "Loki", "Thor");
现在比较每个元素的反向:
Comparator<String> comp = (aName, bName) -> aName.compareTo(bName);
现在,执行排序:
list.stream().sorted(comp.reversed())
以下是使用反向比较器对字符串流进行排序的示例:
import java.util.Arrays; import java.util.Comparator; import java.util.List; public class Demo { public static void main(String[] args) { List<String> list = Arrays.asList("Tom", "Jack", "Ryan", "Kevin", "Loki", "Thor"); System.out.println("Initial List = "+list); System.out.println("Reverse..."); Comparator<String> comp = (aName, bName) -> aName.compareTo(bName); list.stream().sorted(comp.reversed()) .forEach(System.out::println); } }
输出结果
Initial List = [Tom, Jack, Ryan, Kevin, Loki, Thor] Reverse... Tom Thor Ryan Loki Kevin Jack