0

Im trying to sort a hashmap by length of the arraylists I have as the values. My hashmap is:

HashMap<Integer, ArrayList<Integer>> NameofMap = new HashMap<Integer, ArrayList<Integer>>();

I have been trying to use a comparator and collections.sort inline, but it doesnt seem happy with my onject types, and I can't figure out how to fix it. Any help would be greatly appreciated, my code so far is as follows:

Collections.sort(NameofMap.values(), new java.util.Comparator<ArrayList<Integer>>() {
            @Override
            public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {
                return o1.size().compareTo(o2.size());
            }
        });
  • What error do you have? What is `GroupInts` Vs `NameOfMap`? – Gaël J Aug 29 '21 at 13:04
  • 5
    "Im trying to sort a hashmap.." lets stop here. Order of elements in HashMap depends on amount of keys and their hashcode, not on any property of value. You may want to create separate collection which can be sorted like `LinkedHashMap` which preserves insertion order. More info [Sort a Map by values](https://stackoverflow.com/q/109383) – Pshemo Aug 29 '21 at 13:09

1 Answers1

0

You need to edit your code, In your code NameofMap.values() will return a collection which is can not be applicable for the comparable entities, So what you need to do is allocate the value of the hashmap to ArrayList then you can compare the ArrayLists of ArrayList

List<ArrayList<Integer>> l = new ArrayList<>(NameofMap.values());
Collections.sort(l, new Comparator<ArrayList<Integer>>(){
    @Override
    public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2){
        return Integer.compare(o2.size(), o1.size());
    }
});
  • I noticed in one of the comments that I cannot actually sort a hashmap directly, is there some way I can alter this code to convert it to a form that allows for sorting? – Tarasa Bell Aug 29 '21 at 13:59