← Back to libraryQuestion 100 of 273
⌨️Java CodingAdvanced

Sort a Map by Its Values

📌 Definition:

Given a map (e.g. word -> count), produce the entries ordered by value ascending or descending.

📖 Detailed Explanation:

A hash map is unordered, so extract the entries, sort them by value with a comparator (reversed for descending, with a tie-break on the key), and collect into an insertion-ordered structure. The common mistake is expecting the hash map itself to become sorted. O(k log k).

💻 Solutions:
public static Map<String,Integer> sortByValueDesc(Map<String,Integer> map) {
    return map.entrySet().stream()
        .sorted(Map.Entry.<String,Integer>comparingByValue().reversed())
        .collect(java.util.stream.Collectors.toMap(
            Map.Entry::getKey, Map.Entry::getValue,
            (a, b) -> a, LinkedHashMap::new));
}
function sortByValueDesc(obj) {
  return Object.entries(obj)
    .sort((a, b) => b[1] - a[1])
    .reduce((acc, [k, v]) => (acc[k] = v, acc), {});
}
def sort_by_value_desc(d):
    return dict(sorted(d.items(), key=lambda kv: kv[1], reverse=True))
🔑 Key Points:
  • Hash map is unordered — build an ordered result
  • Sort entries by value, tie-break on key
  • Collect into an insertion-ordered map/list
  • O(k log k)
🌍 Real-World Example:

The natural follow-up to frequency counting: "show the top 5 most common failures" — sort a frequency map by value descending.

🎯 Scenario-Based Interview Question:

A candidate sorts the entries then puts them back into a HashMap and the order is lost. Fix?