-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompareStu.java
More file actions
52 lines (38 loc) · 1.35 KB
/
CompareStu.java
File metadata and controls
52 lines (38 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package chapter3;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class CompareStu {
public static void main(String[] args) {
List<Person> people = List.of(new Person("mike", 24), new Person("kangkang", 23), new Person("mary", 20), new Person("jj", 18));
// 根据名字长度排序
System.out.println(people.stream().sorted(Comparator.comparing(p1 -> p1.getName().length() )).collect(Collectors.toList()));
// Person 不实现 Comparable 接口会报错 ClassCastException
System.out.println(people.stream().sorted().collect(Collectors.toList()));
}
public static class Person { // implements Comparable<Person>
private String name;
private Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
// @Override
// public int compareTo(Person person) {
// return age.compareTo(person.getAge());
// }
}
}