Back to Stream: map & Transform
Q21Question 21 of 34

Find the key with the maximum value in a map

Key Concepts
  • entrySet().stream().max(comparingByValue()) returns Optional<Entry> with the largest value
  • Map.Entry.comparingByValue() builds a comparator that orders entries by their value
  • The stream max returns Optional to handle the empty-map case safely
  • Collections.max throws NoSuchElementException on an empty collection
  • If two keys share the maximum value, max returns one arbitrary winner
  • For deterministic tie-breaking, extend the comparator with thenComparing on the key

Definition

entrySet().stream().max(comparingByValue()) finds the entry with the biggest value; map to its key for the answer.
  • Map.Entry.comparingByValue() builds a comparator that orders entries by their value.
  • stream().max(comparator) scans all entries and returns Optional with the largest value.
  • Collections.max(entrySet, comparator) does the same but throws on an empty collection.
  • Ties: max returns one arbitrary winner; chain thenComparing on the key for determinism.

Priya at the National Bank of India has a chart of product to revenue and wants the single best-selling product. She scans every line and picks the one with the biggest number, then reads off its name.

Understanding the Concepts

How do you find the key with the maximum value?

Stream the entrySet, take the max by value, and read the key from the winning entry.

JAVA
package com.bank.products;

import java.util.*;

public class MaxValueKey {
    public static void main(String[] args) {
        Map<String, Double> revenue = Map.of(
            "Savings", 15000.0,
            "Current", 22000.0,
            "Loans",   45000.0,
            "FD",      31000.0
        );

        String topProduct = revenue.entrySet().stream()
            .max(Map.Entry.comparingByValue())
            .map(Map.Entry::getKey)
            .orElse("None");

        System.out.println("Top product: " + topProduct);
    }
}
TEXT
Top product: Loans

How is the stream approach different from Collections.max?

| Feature | stream().max() | Collections.max() |
|---|---|---|
| Empty handling | Returns Optional.empty() | Throws NoSuchElementException |
| Return type | Optional | Entry |
| Null safety | Forces explicit handling | Requires manual guard |

JAVA
// Stream: handles empty map safely
Optional<Map.Entry<String, Double>> opt = revenue.entrySet().stream()
    .max(Map.Entry.comparingByValue());

// Collections: throws on empty
Map.Entry<String, Double> entry = Collections.max(
    revenue.entrySet(), Map.Entry.comparingByValue());

How do you handle ties?

If two products share the maximum revenue, max returns one arbitrary winner. For deterministic selection, extend the comparator.

JAVA
String deterministic = revenue.entrySet().stream()
    .max(Map.Entry.<String, Double>comparingByValue()
        .thenComparing(Map.Entry.comparingByKey()))
    .map(Map.Entry::getKey)
    .orElse("None");

How do you find the key with the minimum value?

Replace max with min.

JAVA
String lowestProduct = revenue.entrySet().stream()
    .min(Map.Entry.comparingByValue())
    .map(Map.Entry::getKey)
    .orElse("None");

What are common mistakes?

Mistake: using Collections.max on a potentially empty map.

JAVA
// WRONG: throws on empty map
Map<String, Double> empty = Map.of();
var entry = Collections.max(empty.entrySet(),
    Map.Entry.comparingByValue());  // NoSuchElementException!

// CORRECT: stream().max() returns Optional
String safe = empty.entrySet().stream()
    .max(Map.Entry.comparingByValue())
    .map(Map.Entry::getKey)
    .orElse("No products");

What should a senior engineer know?

  • max scans every entry once, so time complexity is O(n).
  • The Optional chain (max then map then orElse) is the idiomatic way to extract the key safely.
  • For the top N keys by value, use sorted(comparingByValue().reversed()).limit(n) instead of max.
  • comparingByValue() uses natural ordering of the value type. For custom ordering, pass a comparator argument.

What are common interview follow-up questions?

  • "How do you find the top 3 keys by value?" sorted(comparingByValue().reversed()).limit(3).
  • "How do you find the entry with the maximum key?" Use comparingByKey() instead.
  • "What if values are null?" comparingByValue throws NPE; filter nulls first.

Visual Overview

DIAGRAM
  Map<String, Double>
  {Savings=15K, Current=22K, Loans=45K, FD=31K}
       │
       │  entrySet().stream().max(comparingByValue())
       ▼
  Scan:
    Savings=15K  → current max = Savings(15K)
    Current=22K  → current max = Current(22K)
    Loans=45K    → current max = Loans(45K)    ← new max
    FD=31K       → current max = Loans(45K)    (31K < 45K)
       │
       ▼
  Optional[Loans=45000.0]
       │  .map(Entry::getKey)
       ▼
  Optional["Loans"]
       │  .orElse("None")
       ▼
  "Loans"

Key Takeaway

To find the key with the largest value, stream the entrySet, take max with comparingByValue(), then map the winning entry to its key. The stream max returns Optional, which forces safe handling of the empty-map case.

At the National Bank of India, this found the top-revenue product from a product-to-revenue map. Prefer the stream approach over Collections.max because it returns Optional instead of throwing on an empty collection.

For deterministic tie-breaking, extend the comparator with thenComparing on the key. For the top N, replace max with sorted().limit(n).

Remember one sentence: entrySet().stream().max(comparingByValue()) finds the entry with the largest value in O(n), and map to getKey extracts the answer.

---

Share
Use ← → arrow keys to navigate