优先级如下:
年龄小于等于18岁的排在前面 -> 女士排在男士前边 -> 体重沉的排在体重轻的前边
测试集
Person p1 = new Person(16,"男",90);
Person p2 = new Person(18,"女",98);
Person p3 = new Person(6,"男",70);
Person p4 = new Person(30,"男",120);
Person p5 = new Person(45,"女",130);
Person p6= new Person(60,"女",140);
Person p7 = new Person(55,"男",160);
class Person{
private int age;
private String sex;
private int weight;
public Person(){}
public Person(int age, String sex, int weight) {
this.age = age;
this.sex = sex;
this.weight = weight;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", sex='" + sex + '\'' +
", weight=" + weight +
'}';
}
}
java 8 的计算方式
List<Person> peoples= Arrays.asList(p1, p2, p3, p4, p5, p6, p7);
Comparator<Person> comparator = Comparator
.comparing((Person x)->x.getAge()<=18)
.thenComparing((Person x)->x.getSex().equals("女"))
.thenComparing(Person::getWeight).reversed();
peoples.stream().sorted(comparator).forEach(System.out::println);