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) {
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
  • close this too.. God bless stackoverflow – Prabhat Gaur Nov 24 '19 at 16:31
  • You can't sort a `HashMap` because a `HashMap` has no specified order... – Slaw Nov 24 '19 at 16:37
  • yes but people are sorting it by keys and values too! – Prabhat Gaur Nov 24 '19 at 16:38
  • "but people are sorting it by keys and values too" no, we are NOT sorting hashmap but List of that map *entries* (lists can be sorted). – Pshemo Nov 24 '19 at 16:38
  • Nobody is sorting a `HashMap` because you _can't sort a `HashMap`_. Use a `SortedMap` to have a map sorted by the keys or a `LinkedHashMap` to maintain insertion order. – Slaw Nov 24 '19 at 16:39
  • 3
    What answer are you looking for? Your question is how to sort a `HashMap` by its values and the answer to that is you can't. Sorting a `HashMap` is _impossible_. Full stop. You can take the entries, put them in a list, and then sort the list but that has no effect on the `HashMap` because, again, you _cannot sort a `HashMap`_. – Slaw Nov 24 '19 at 16:45
  • https://www.java67.com/2015/01/how-to-sort-hashmap-in-java-based-on.html – Prabhat Gaur Nov 24 '19 at 16:47
  • still they will sort it – Prabhat Gaur Nov 24 '19 at 16:48
  • 2
    The link you gave shows that they are not storing the sorted map in a `HashMap`, but rather in a `LinkedHashMap`. As you were already told - it can't be done with the original `HashMap`. – RealSkeptic Nov 24 '19 at 16:49

0 Answers0