How to sort Map values by key in Java?

后端 未结 15 2461
野性不改
野性不改 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:15

    Using Java 8:

    Map sortedMap = unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
    

提交回复
热议问题