javasortinghashmapjava-streamalphabetical

How to sort HashMap of String and Integer, by value and in case of duplicate then sort them by key, Including Russian words


How can I sort a HashMap, with first by values, then in case the values are the same sort them by alphabetically, including Russian words.?

The correct output should look like this (Strings are keys, Integers are values):

лицами-18
Apex-15
azet-15
xder-15
анатолю-15
андреевич-15
батальона-15
hello-13
zello-13
полноте-13

I was able to sort them only by values, but I am unable to sort them when the keys are the same.

The following code helped me, however it only works for single chars:

private static Map<String, Integer> sortByValue(Map<String, Integer> unsortMap, final boolean order)
{
    List<Entry<String, Integer>> list = new LinkedList<>(unsortMap.entrySet());

    // Sorting the list based on values
    list.sort((o1, o2) -> order ? o1.getValue().compareTo(o2.getValue()) == 0
            ? o1.getKey().compareTo(o2.getKey())
            : o1.getValue().compareTo(o2.getValue()) : o2.getValue().compareTo(o1.getValue()) == 0
            ? o2.getKey().compareTo(o1.getKey())
            : o2.getValue().compareTo(o1.getValue()));
    return list.stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue, (a, b) -> b, LinkedHashMap::new));

}

private static void printMap(Map<String, Integer> map)
{
    map.forEach((key, value) -> System.out.println("Key : " + key + " Value : " + value));
}

Solution

  • I would do something like this:

            List<String> sortedEntries = unsortMap.entrySet().stream()
                .sorted(Comparator.comparingLong(Map.Entry<String, Integer>::getValue)
                        .reversed()
                        .thenComparing(Map.Entry::getKey)
                )
                .map(it -> it.getKey() + "-" + it.getValue())
                .collect(Collectors.toList());