Saturday, February 8, 2020

Retrieve data from a Map reverse-ordered by value and then ordered by key


Problem

Given a Map of strings to their frequencies. Find top N-most frequent strings. If there is a tie get lexicographically smallest names first.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
List<String> findTopNNames(Map<String, Integer> data, int n) {
    Comparator<Map.Entry<String, Integer>> cmpByValueDesc =
        Map.Entry.comparingByValue(Comparator.reverseOrder());

    Comparator<Map.Entry<String, Integer>> cmpByKey =
        Map.Entry.comparingByKey();

    Comparator<Map.Entry<String, Integer>> cmp =
        cmpByValueDesc.thenComparing(cmpByKey);

    return data.entrySet().stream()
        .sorted(cmp)
        .map(Map.Entry::getKey)
        .limit(n)
        .collect(Collectors.toList());
}

No comments:

Post a Comment