将HashMap通过value或value对象中的某个变量、对象进行排序,首先要将value取出保存在list里面,这里以value为student对象为例
//方法一:直接获取values集合
public static void sortByScore(Map<Integer, Student> m1) {
//获取map的value集合
Collection<Student> c1 = m1.values();
//将value集合存入list
List<Student> l1 = new ArrayList<Student>(c1);
/*
如果需要对每个数据做处理,可以使用迭代器遍历添加
List<Student> l1 = new ArrayList<Student>();
Iterator<Student> iter = c1.iterator();
Student s1 = new Student();
while(iter.hasNext()) {
s1 = iter.next();
s1.setId(11);
l1.add(s1);
}
*/
Collections.sort(l1,new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
//这里通过sroce排序
return o1.getSroce().compareTo(o2.getSroce());
//相当于return o1.getSroce()-o2.getSroce();
}
});
}
//方法二:获取map的entry集合
public static void sort(Map<Integer, Student> m1) {
//获取map的entrySet集合
Set<Entry<Integer, Student>> es = m1.entrySet();
//将entry集合存入list
List<Entry<Integer, Student>> l1 = new ArrayList<>(es);
Collections.sort(l1, new Comparator<Entry<Integer, Student>>() {
@Override
public int compare(Entry<Integer, Student> o1, Entry<Integer, Student> o2) {
//通过获取entry的value(Student对象),再获取分数进行比较
return o1.getValue().getSroce().compareTo(o2.getValue().getSroce());
}
});
}