在一次采访中,我被要求按值对 HashMap 进行排序。即使在我编写了这样的程序之后,它也不会按排序顺序打印 HashMap。有人可以解释一下吗?
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<Integer,String> x= new HashMap<Integer,String>();
x.put(3, "arsfd");
x.put(5, "3453");
x.put(6, "sdfsaf");
x.put(8, "wetr");
x.put(11, "cbncvnbv");
List<String> mylist = new ArrayList<String>();
mylist.addAll(x.values());
Collections.sort(mylist);
HashMap<Integer,String> y= new HashMap<Integer,String>();
for(int p=0;p<x.size();p++) {
System.out.println(mylist.get(p));
y.put((Integer) getKey(x,mylist.get(p)), mylist.get(p));
}
System.out.println(y.toString());
}
public static Integer getKey(HashMap<Integer,String> x,Object v) {
for(Entry<Integer, String> oo:x.entrySet()) {
if(oo.getValue()==v)
return (Integer)oo.getKey();
}
return null;}