HashMap集合實現對對象引用數據類型的排序

//創建測試類

package MapSortDemo;

//實現Compatable<T>接口
public class Student implements Comparable<Student>{
    private String name;
    private int age;
    private int secore;

    public Student() {
    }

    public Student(String name, int age, int secore) {
        this.name = name;
        this.age = age;
        this.secore = secore;
    }

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


    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public int getSecore() {
        return secore;
    }

    public void setSecore(int secore) {
        this.secore = secore;
    }

    //重寫compareTo()方法,改寫排序規則,此處通過Student中的secore升序排序
    @Override
    public int compareTo(Student o) {
        return this.secore - o.secore;
    }
}
package MapSortDemo;

import java.util.*;

public class MapObjSort {
    public static void main(String[] args) {
        HashMap<Student,String> has = new HashMap<>();
        has.put(new Student("張三",18,98),"001A");
        has.put(new Student("李四",23,77),"004A");
        has.put(new Student("王五",41,32),"003A");
        has.put(new Student("劉兒",85,41),"005A");
        Set<Student> keys = has.keySet();
        ArrayList<Student> arr = new ArrayList<>();
        arr.addAll(keys);
        Collections.sort(arr, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o2.getAge() - o1.getAge();
            }
        });
        for (Student student : arr) {
            String val = has.get(student);
            System.out.println(student + "=" + val);
        }
    }
}
//運行結果
Student{name='劉兒', age=85, secore=41}=005A
Student{name='王五', age=41, secore=32}=003A
Student{name='李四', age=23, secore=77}=004A
Student{name='張三', age=18, secore=98}=001A
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章