How can I sort a Map based upon on the size of its Collection values?

后端 未结 2 1332
你的背包
你的背包 2020-12-08 23:36

I have a HashMap like this:

Map> map = new HashMap<>();

map.put(\"USA\", Arrays.asList(\"CA\",\"IA\",\"I         


        
2条回答
  •  清歌不尽
    2020-12-08 23:50

    You have two problems.

    1. Map doesn't support sorting.

    2. SortedMap doesn't support sorting on values only sorting on keys.

    As a result of this using a Map or SortedMap isn't going to help you. What you need to do is iterate over you map and put each Entry> into a collection such as a List and then sort the list with a custom compare. See this example TreeMap sort by value or this example Sorting LinkedHashMap

提交回复
热议问题