Md Johirul Islam Md Johirul Islam - 5 months ago 13
Java Question

How to sort HashMap in java depending on the size of value List

I have a hashmap like the following

HashMap<String, ArrayList<String>> map=new HashMap<String, ArrayList<String>>();

map.put("USA", Arrays.asList("CA","IA","IL"));
map.put("India", Arrays.asList("MUM","CAL"));
map.put("Canada", Arrays.asList("TOR"));

I want to sort the map depending on the size of the list in the value in ascending order.How can i do that. Is there any nice method to do so?


Use a TreeMap which is sorted by key so flip the map:

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Test {
    public static void main(String[] args) {
        Map<String, List<String>> map = new HashMap<String, List<String>>();

        map.put("USA",Arrays.asList(new String[]{"CA","IA","IL"}));
        map.put("India",Arrays.asList(new String[]{"MUM","CAL"}));
        map.put("Canada",Arrays.asList(new String[]{"TOR"}));

        System.out.println("original list:");

        for( Map.Entry<String, List<String>> entry : map.entrySet() ) {
            System.out.println(entry.getKey() + " => " + entry.getValue() );

        Map<List<String>, String> navigableMap = new TreeMap<List<String>, String>( new Comparator<List<String>>(){
            public int compare(List<String> arg0, List<String> arg1) {
                return arg0.size() - arg1.size();
        } );

        for( Map.Entry<String, List<String>> entry : map.entrySet() ) {
            navigableMap.put(entry.getValue(), entry.getKey());

        System.out.println("sorted map:");

        for( Map.Entry<List<String>, String> entry : navigableMap.entrySet() ) {
            System.out.println(entry.getValue() + " => " + entry.getKey() );


Which outputs:

original list:
USA => [CA, IA, IL]
Canada => [TOR]
India => [MUM, CAL]
sorted map:
Canada => [TOR]
India => [MUM, CAL]
USA => [CA, IA, IL