TreeMap类型实体类外部比较器进行排序

实体类StudentWaiBuCompare代码如下所示:

package com.test.Test11;


public class StudentWaiBuCompare{
    private int age;
    private String name;
    private Double height;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getHeight() {
        return height;
    }

    public void setHeight(Double height) {
        this.height = height;
    }

    public StudentWaiBuCompare(int age, String name, Double height) {
        this.age = age;
        this.name = name;
        this.height = height;
    }

    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", height=" + height +
                '}';
    }

}

测试类Test.java如下所示:


package com.test.Test11;

import java.util.Comparator;
import java.util.TreeMap;

public class Test03WaiBuCompare {
    public static void main(String[] args) {
        //TreeMap 唯一,有序(按升序或者降序排序)
        TreeMap map = new TreeMap<>(new Comparator() {
            @Override
            public int compare(StudentWaiBuCompare o1, StudentWaiBuCompare o2) {
                //return 0;
                return ((Double)(o1.getHeight())).compareTo((Double)(o2.getHeight()));
            }
        });

        map.put(new StudentWaiBuCompare(19,"blili",170.5), 1001);
        map.put(new StudentWaiBuCompare(18,"blili",150.5), 1003);
        map.put(new StudentWaiBuCompare(19,"alili",180.5), 1023);
        map.put(new StudentWaiBuCompare(17,"clili",140.5), 1671);
        map.put(new StudentWaiBuCompare(10,"dlili",160.5), 1891);
        System.out.println(map.size()); //5
        //按照身高进行排列
        System.out.println(map);
        //res:{Student{age=17, name='clili', height=140.5}=1671, Student{age=18, name='blili', height=150.5}=1003, Student{age=10, name='dlili', height=160.5}=1891, Student{age=19, name='blili', height=170.5}=1001, Student{age=19, name='alili', height=180.5}=1023}

    }
}

你可能感兴趣的:(java,java,开发语言)