使用TreeSet對Map的值的元素進行排序
阿新 • • 發佈:2018-12-10
import java.util.Comparator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
class Student1{
String name;
int age;
int score;
public Student1(String name, int age, int score) {
super();
this.name = name;
this.age = age;
this .score = score;
}
@Override
public String toString() {
return "Student1 [name=" + name + ", age=" + age + ", score=" + score + "]";
}
}
public class HashMapSortDemo {
public static void main(String[] args) {
TreeMap<String, Student1> hashmap = new TreeMap<>();
Student1 s1 = new Student1("小明1",18,88);
Student1 s2 = new Student1("小明2",13,28);
Student1 s3 = new Student1("小明3",15,48);
Student1 s4 = new Student1("小明4",17,558);
Student1 s5 = new Student1("小明5",344,58);
hashmap.put(s1.name, s1);
hashmap.put(s2.name, s2);
hashmap.put(s3.name, s3);
hashmap.put(s4.name, s4);
hashmap.put(s5.name, s5);
TreeMap<String, Student1> sortMap = new TreeMap<>(new Comparator<String>() {
//按照年齡排序
// @Override
// public int compare(String o1, String o2) {
// int num = hashmap.get(o1).age - hashmap.get(o2).age;
// return num;
// }
//按照成績排序
@Override
public int compare(String o1, String o2) {
int num = hashmap.get(o1).score - hashmap.get(o2).score;
return num;
}
});
sortMap.putAll(hashmap);
Set<Entry<String,Student1>> entrySet = sortMap.entrySet();
entrySet.forEach(c -> System.out.println(c.getKey()+"--"+c.getValue()));
}
}