0

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;}
Prabhat Gaur
  • 146
  • 1
  • 10
  • 1
    The question makes no sense. You could use another Map implementation that preserves insertion order, or create a list of entries and sort that list. But not sort a HashMap. – JB Nizet Nov 24 '19 at 13:36
  • @TimBiegeleisen SortedMaps orders their entries by their key, not their value. – JB Nizet Nov 24 '19 at 13:37
  • 1
    @JBNizet Of course I knew that, I was just making sure you were paying attention `:-)` – Tim Biegeleisen Nov 24 '19 at 13:38
  • reopen my question – Prabhat Gaur Nov 24 '19 at 14:20
  • 1
    Read [Sort a Map by values](https://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values) for options. TL;DR: `HashMap` itself cannot be sorted, but you can sort its entries and then store them in a `LinkedHashMap` which conserves insertion order. – Malte Hartwig Nov 25 '19 at 06:20

0 Answers0