Java List 集合排序:使用函数式接口 Comparator
Java 中可以使用函数式接口 'Comparator' 对 'List' 集合进行排序。'Comparator' 是一个函数式接口,其中有一个 'compare' 方法,用于比较两个对象的大小关系。在使用 'Comparator' 排序时,可以使用 Lambda 表达式或方法引用来实现 'compare' 方法。
示例代码如下:
List<String> list = Arrays.asList('apple', 'banana', 'orange', 'grape');
// 使用 Lambda 表达式排序
list.sort((s1, s2) -> s1.compareTo(s2));
System.out.println(list);
// 使用方法引用排序
list.sort(String::compareTo);
System.out.println(list);
输出结果为:
[apple, banana, grape, orange]
[apple, banana, grape, orange]
在上面的代码中,我们首先创建了一个包含几个水果名称的 'List' 集合,然后使用 Lambda 表达式和方法引用分别对 'List' 进行了排序。Lambda 表达式和方法引用都使用了 'String' 类的 'compareTo' 方法来实现 'compare' 方法的比较逻辑。最后输出排序后的 'List' 集合。
原文地址: https://www.cveoy.top/t/topic/oU9r 著作权归作者所有。请勿转载和采集!