How to sort Map values by key in Java?

后端 未结 15 2381
野性不改
野性不改 2020-11-22 08:26

I have a Map that has strings for both keys and values.

Data is like following:

\"question1\", \"1\"
\"question9\", \"1\"
\"que

15条回答
  •  深忆病人
    2020-11-22 09:09

    Just in case you don't wanna use a TreeMap

    public static Map sortByKey(Map map) {
            List> list = new ArrayList<>(map.entrySet());
            list.sort(Comparator.comparingInt(Map.Entry::getKey));
            Map sortedMap = new LinkedHashMap<>();
            list.forEach(e -> sortedMap.put(e.getKey(), e.getValue()));
            return sortedMap;
        }
    

    Also, in-case you wanted to sort your map on the basis of values just change Map.Entry::getKey to Map.Entry::getValue

提交回复
热议问题