首页javamapJava Collection - 如何在HashMap的属性上排序对象,而不是值

Java Collection - 如何在HashMap的属性上排序对象,而不是值

我们想知道如何在HashMap的属性上排序对象,而不是值。
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Main {
  public static void main(String[] args) {
    Map<String, Student> map = new HashMap<>();
    map.put("s1", new Student(5, "A"));
    map.put("s2", new Student(4, "B"));
    map.put("s3", new Student(10, "C"));
    map.put("s4", new Student(2, "D"));
    Collection<Student> students = map.values();
    List<Student> list = new ArrayList<>(students);
    Collections.sort(list, new MyComparator());

    for (Iterator<Student> it = list.iterator(); it.hasNext();) {
      Student stdn = (Student) it.next();
      System.out.println("Student id : " + stdn.id);
      System.out.println("Student Name : " + stdn.name);
    }
  }
}

class MyComparator implements Comparator<Student> {

  @Override
  public int compare(Student s1, Student s2) {
    return s1.name.compareTo(s2.name);
  }
}

class Student {
  int id;
  String name;

  Student(int id, String name) {
    this.id = id;
    this.name = name;
  }
}