一個排序問題

優先級如下:

年齡小於等於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);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章