在一次采访中,我被要求按值对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;}