How to sort HashMap when HashMap does not maintain insertion order?

65 Views Asked by At

In an interview I was asked to sort HashMap by values. Even after I write such a program, it does not print the HashMap in sorted order. Can someone please explain?

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;}
0

There are 0 best solutions below