List 作为常用数据结构,有时候需要对里面的元素进行排序,这个排序规则有可能是元素对象的一个属性字段,这里简单介绍一个 List 自带的排序功能和 Stream 的排序功能。 List 自带的排序功能是 List 自己的接口,不是继承自 Collection。
先创建一个实体类
class Student {
Integer age;
String name;
Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
创建几个对象
Student student1 = new Student("s1", 10);
Student student2 = new Student("s2", 3);
Student student3 = new Student("s3", -1);
Student student4 = new Student("s4", 20);
Student student5 = new Student("s4", 5);
- List 自带的排序功能
List<Student> list = new ArrayList<>();
list.add(student1);
list.add(student2);
list.add(student3);
list.add(student4);
list.add(student5);
System.out.println("排序前");
list.forEach(student -> System.out.println(student));
System.out.println("排序后");
list.sort(Comparator.comparing(Student::getAge));
list.forEach( student -> System.out.println(student));
这里的可以看出排序字段可以是 Integer类型,也可以是 Double、Long
根据某个字段排序后,还可以再根据另外一个字段继续排序
降序排序
System.out.println("排序前");
list.forEach(student -> System.out.println(student));
System.out.println("排序后");
list.sort(Comparator.comparing(Student::getAge).reversed());
list.forEach(student -> System.out.println(student));
- stream 的排序功能
System.out.println("排序前");
list.forEach(student -> System.out.println(student));
list.stream().sorted(Comparator.comparing(Student::getAge));
System.out.println("排序后");
list.forEach( student -> System.out.println(student));
发现是没有排序成功的,原因是 stream 就像一个流一样,流过一个功能接口就对上一次的数据进行操作,并不会改变原来的 List 的元素。需要用新的 List 的集合去接收。
用新的 List 集合去接收
System.out.println("排序前");
list.forEach(student -> System.out.println(student));
List<Student> newList = list.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
System.out.println("排序后");
newList.forEach(student -> System.out.println(student));
其他的排序规则跟 List 自带的排序一样,因为都是用同一个接口 Comparator
- Collections.sort 排序
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int io1 = sortList .indexOf(s1);
int io2 = sortList .indexOf(s2);
return io1 - io2;
}
});
里面的 sortList 的已经按照自己想要的排序规则排序好的集合,list是想要被排序的集合,这段代码实现的功能是将 list 按照 sortList 的规则排序。
- Set 集合排序后转化成 List 集合
Set<Student> set = new HashSet<>();
set.add(student1);
set.add(student2);
set.add(student3);
set.add(student4);
set.add(student5);
System.out.println("排序前");
set.forEach(student -> System.out.println(student));
List<Student> newList = set.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
System.out.println("排序前");
newList.forEach(student -> System.out.println(student));