Java List排序:Comparable与Comparator接口及Stream API应用
在 Java 编程中,集合(List)元素排序是常见需求。本文将解读使用 Comparable 接口、Comparator 接口及 JDK 8 的 Stream API 对 List 进行高效排序,并通过实例代码演示用法和区别。
Comparable接口
原理与应用
java.lang.Comparable
是 Java 标记型接口,定义了compareTo(T o)
方法,实现该接口的类可进行比较排序,像 Integer、String 等内置类型已实现,它确定了自然排序规则
public interface Comparable<T> {
int compareTo(T o);
}
我们创建了一个Person
类并实现Comparable
接口,指定按照年龄排序,当你调用Collections.sort()
对Person对象列表进行排序时,无需额外提供排序规则,因为Person
类自身已经定义了如何与其他Person
对象进行比较。
public class Person implements Comparable<Person> {
private String name;
private int age;
// 构造函数,getters, setters...
@Override
public int compareTo(Person other) {
return Integer.compare(this.age, other.age);
}
}
List<Person> people = ...; // 初始化人员列表
Collections.sort(people); // 这里调用sort时,会自动使用Person类中定义的compareTo方法进行排序
Comparator接口
原理与应用
java.util.Comparator
是另一个接口,它也提供了比较两个对象的方法,但是它的比较逻辑是外在的,不依赖于被比较对象本身的实现,它可以为任何类提供多种不同的排序策略。
public interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
}
我们可能需按姓名或年龄对 Person 对象排序,可创建两个不同 Comparator,同一个 Person 类可依不同 Comparator 产生不同排序结果,这是外部排序的灵活性
import java.util.Comparator;
public class AgeComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
return Integer.compare(p1.getAge(), p2.getAge());
}
}
public class NameComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
return p1.getName().compareTo(p2.getName());
}
}
// 使用:
List<Person> people = ...;
Collections.sort(people, new AgeComparator()); // 按年龄排序
Collections.sort(people, new NameComparator()); // 按姓名排序
Stream API中的排序
Java 8 的 Stream API 引入了链式编程风格,sorted()
方法可用于对流元素排序,能接受Comparator
参数,若元素类型已实现Comparable
接口,可直接调用sorted()
无需传参
List<Person> people = Arrays.asList(...); // 初始化人员列表
// 使用Stream API和lambda表达式按年龄排序
List<Person> sortedByAge = people.stream()
.sorted(Comparator.comparing(Person::getAge)) // 使用方法引用简化代码
.collect(Collectors.toList());
// 或者直接在原始list上排序(不创建新的list)
people.sort(Comparator.comparing(Person::getAge));
区别总结
- Comparable:内部排序,适用于有固有排序逻辑的实体,在类中实现接口进行内部排序。
- Comparator:外部排序,更灵活,可按需动态指定或切换排序规则,创建实现类进行外部排序。
- Stream API 排序:结合 Lambda 表达式简化代码、增强可读性,可链式操作,利用
sorted()
方法配合 Lambda 表达式或 Comparator 对集合元素排序并与其他流操作结合。
What is Java technology and why do I need it?
Java is a programming language and computing platform first released by Sun Microsystems in 1995. It has evolved from humble beginnings to power a large share of today’s digital world, by providing the reliable platform upon which many services and applications are built. New, innovative products and digital services designed for the future continue to rely on Java, as well.
While most modern Java applications combine the Java runtime and application together, there are still many applications and even some websites that will not function unless you have a desktop Java installed. Java.com, this website, is intended for consumers who may still require Java for their desktop applications – specifically applications targeting Java 8. Developers as well as users that would like to learn Java programming should visit the dev.java website instead and business users should visit oracle.com/java for more information.
Is Java free to download?
Yes, Java is free to download for personal use.
Java is also free for development: developers can find all the development kits and other useful tools at https://www.oracle.com/javadownload/.
Why should I upgrade to the latest Java patch each quarter when prompted?
The latest Java patches contain important enhancements to improve performance, stability and security of the Java applications that run on your machine. Installing these updates will ensure that your Java applications continue to run with the most up-to-date version.