当HashMap不保持插入顺序时,如何对HashMap进行排序?

在一次采访中,我被要求按值对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;}
xiaoover 回答:当HashMap不保持插入顺序时,如何对HashMap进行排序?

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3041807.html

大家都在问