hashMap会自动根据键来排序,但是有时我们想根据值来排序,那应该怎么做呢
答案就是用collections.sort()方法.
public class HashMapTest {
public static void main(String[] args) {
HashMap<String, person> map=new HashMap<String,person>();
map.put("x",new person("aa",27));
map.put("e",new person("ee",26));
map.put("q",new person("cc",22));
map.put("f",new person("bb",23));
map.put("s",new person("ff",24));
map.put("z",new person("dd",25));
Set<Map.Entry<String,person>> mm=map.entrySet();
ArrayList<Map.Entry<String,person>> arr=new ArrayList<Map.Entry<String,person>>(mm);
Collections.sort(arr,new Comparator<Map.Entry<String,person>>() {
@Override
public int compare(Map.Entry<String,person> o1, Map.Entry<String,person> o2) {
return (o1.getValue().getAge()+"").compareTo(o2.getValue().getAge()+"");
}
});
for (Map.Entry<String,person> x:arr){
System.out.println(x.getKey()+" "+x.getValue().getName()+" "+x.getValue().getAge());
}
}
}