import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Test {
@Data
@NoArgsConstructor
@AllArgsConstructor
static class Sport implements Comparable<Sport> {
// 体育权重
private Integer weight;
@Override
public int compareTo(Sport o) {
return this.getWeight().compareTo(o.getWeight());
}
}
@Data
static class BasketBall extends Sport {
// 位置:前锋、后卫、中锋
private String address;
public BasketBall(Integer weight, String address) {
super(weight);
this.address = address;
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
static class Person {
private String age;
}
@Data
static class User extends Person {
private Sport sport;
public User(String type, Sport sport) {
super(type);
this.sport = sport;
}
}
public static void main(String[] args) {
List<User> userList = Lists.newArrayList();
User c1 = new User("加菲猫", new BasketBall(10, "前锋"));
User c2 = new User("蓝猫", new BasketBall(20, "后卫"));
userList.add(c1);
userList.add(c2);
// 使用父类的属性排序
System.out.println(userList.stream().sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList()));
// 定义的是根据Sport的排序,但实际的类型是BasketBall
Comparator<User> c = Comparator.comparing(User::getSport);
System.out.println(userList.stream().sorted(c).collect(Collectors.toList()));
}
}
comparing静态方法分析
最新推荐文章于 2024-11-02 11:13:42 发布
本文展示了如何在Java中使用继承和Comparator接口对User对象列表进行排序,首先按照Person的年龄,然后根据扩展类BasketBall的体育权重进行排序。
摘要由CSDN通过智能技术生成