Sort Map by Value

Java coding interview problem for Collections: Sort Map by Value.

Sorting a Map by value is a common Java Collections interview problem.

Unlike Lists, Maps are primarily designed for:

Key → Value lookup

not sorting.

A Map stores data like:

Employee ID → Salary

Product ID → Price

Word → Frequency

Sometimes we need to sort based on the value.

Example:

Word Frequency Map

java   → 5

spring → 3

boot   → 1

Sorted by value:

boot   → 1

spring → 3

java   → 5

What is Sorting a Map?

Sorting a Map means arranging entries based on a specific rule.

A Map entry contains:

Key + Value

Example:

Map<String,Integer>

Data:

Apple  → 50

Banana → 20

Orange → 80

Sort by value ascending:

Banana → 20

Apple  → 50

Orange → 80

Sort by value descending:

Orange → 80

Apple  → 50

Banana → 20

Key Sorting vs Value Sorting

There are two different sorting operations.


Sort by Key

Example:

Input:

Java → 5

Spring → 3

Boot → 1

Sorted key:

Boot → 1

Java → 5

Spring → 3

Common solution:

TreeMap

Sort by Value

Example:

Input:

Java → 5

Spring → 3

Boot → 1

Sorted value:

Boot → 1

Spring → 3

Java → 5

Requires:

Comparator

Understanding Map Data Structure

A Map stores:

Key

 |

Value

Example:

101 → John

102 → Alice

103 → Bob

Internally:

HashMap

    |

Buckets

    |

Nodes

    |

(key,value)

Why Map Values Need Sorting?

Many applications store data in maps.

Examples:


Word Frequency Analysis

Input:

java spring java boot java

Map:

java → 3

spring → 1

boot → 1

Sort by frequency:

spring → 1

boot → 1

java → 3

Employee Salary Ranking

Map:

Employee → Salary

Sort:

Highest salary first

Product Ranking

Map:

Product → Sales Count

Sort:

Most sold products

Real-World Applications

Search Engines

Rank results based on:

Score

Frequency

Relevance

E-Commerce

Sort products by:

Sales count

Rating

Price

Banking Systems

Sort customers by:

Account balance

Transaction volume

Analytics Systems

Sort metrics:

Error count

Request count

Response time

Problem Statement

Given a Map containing key-value pairs, sort the map based on values.


Example 1

Input:

{
 "Java" = 5,
 "Spring" = 3,
 "Boot" = 1
}

Output:

Ascending:

Boot=1

Spring=3

Java=5

Example 2

Input:

{
 "A" = 100,
 "B" = 20,
 "C" = 50
}

Output:

Descending:

A=100

C=50

B=20

Map.Entry Concept

A Map contains entries:

Map.Entry<K,V>

Example:

Map.Entry<String,Integer>

represents:

Key

+

Value

Example:

Java=5

is:

Entry

Key   = Java

Value = 5

Why Map.Entry is Required?

A Map cannot directly sort values.

We convert:

Map

 ↓

Set of Entries

 ↓

List

 ↓

Sort

 ↓

LinkedHashMap

Sorting Flow

HashMap

    |

entrySet()

    |

List<Entry>

    |

Comparator

    |

Sorted Entries

    |

LinkedHashMap

HashMap Internal Working

HashMap provides:

O(1)

average lookup.

But:

HashMap has no ordering

Example:

Insertion:

Java

Spring

Boot

Output may be:

Boot

Java

Spring

Therefore:

We need another Map:

LinkedHashMap

to maintain sorted order.


Approach 1 — Convert Map Entries to List

The most common approach:

Steps:

  1. Convert Map entries to List.
  2. Sort list using Comparator.
  3. Store result in LinkedHashMap.

Algorithm

Given:

Map<K,V>

Step 1:

Convert:

map.entrySet()

to:

List<Entry<K,V>>

Step 2:

Sort entries:

Comparator

Step 3:

Insert into:

LinkedHashMap

Java Program — Sort Map By Value Ascending

import java.util.*;

public class SortMapByValue {


    public static Map<String,Integer>
    sortByValue(
            Map<String,Integer> map) {


        List<Map.Entry<String,Integer>> entries =
                new ArrayList<>(
                    map.entrySet()
                );


        entries.sort(
            Map.Entry.comparingByValue()
        );


        Map<String,Integer> result =
                new LinkedHashMap<>();


        for(Map.Entry<String,Integer> entry :
                entries) {


            result.put(
                entry.getKey(),
                entry.getValue()
            );

        }


        return result;

    }


    public static void main(String[] args) {


        Map<String,Integer> map =
                new HashMap<>();


        map.put("Java",5);

        map.put("Spring",3);

        map.put("Boot",1);


        System.out.println(
            sortByValue(map)
        );

    }

}

Output

Boot=1

Spring=3

Java=5

Step-by-Step Explanation

Input:

Java=5

Spring=3

Boot=1

Convert entries:

[
 Java=5,

 Spring=3,

 Boot=1
]

Sort values:

Before:

5,3,1

After:

1,3,5

Sorted list:

Boot=1

Spring=3

Java=5

Insert into LinkedHashMap:

Boot → 1

Spring → 3

Java → 5

Complexity Analysis

Let:

n = number of entries

Converting:

O(n)

Sorting:

O(n log n)

Creating result:

O(n)

Total:

O(n log n)

Space:

O(n)

because:

  • Entry list
  • Result map

Advantages

  • Simple.
  • Interview preferred.
  • Works with any value type.
  • Easy customization.

Drawbacks

  • Requires extra memory.
  • Sorting is not possible directly on HashMap.

Approach 2 — Comparator Based Sorting

Instead of:

comparingByValue()

we can write:

Comparator

Example:

entries.sort(
    (entry1, entry2) ->
        entry1.getValue()
        -
        entry2.getValue()
);

Sorting Map Values in Descending Order

The previous approach sorted values in ascending order.

Many interview problems require:

Highest value first

Example:

Input:

Java = 5

Spring = 3

Boot = 1

Output:

Java = 5

Spring = 3

Boot = 1

Comparator Reverse Ordering

Use:

Collections.reverseOrder()

or:

Comparator.reversed()

Java Program — Sort Map By Value Descending

import java.util.*;

public class SortMapDescending {


    public static Map<String,Integer>
    sortDescending(
            Map<String,Integer> map) {


        List<Map.Entry<String,Integer>> entries =
                new ArrayList<>(
                    map.entrySet()
                );


        entries.sort(
            Map.Entry
            .comparingByValue()
            .reversed()
        );


        Map<String,Integer> result =
                new LinkedHashMap<>();


        for(Map.Entry<String,Integer> entry :
                entries) {


            result.put(
                entry.getKey(),
                entry.getValue()
            );

        }


        return result;

    }

}

Output

Input:

Java=5

Spring=3

Boot=1

Output:

Java=5

Spring=3

Boot=1

Java 8 Lambda Comparator

We can also write:

entries.sort(
    (e1,e2) ->
        e2.getValue()
        -
        e1.getValue()
);

Explanation:

Ascending:

e1.value - e2.value

Descending:

e2.value - e1.value

Important Note

Avoid subtraction comparison for large numbers:

Wrong:

e1.getValue()
-
e2.getValue()

because integer overflow can occur.


Better:

Integer.compare(
    e2.getValue(),
    e1.getValue()
);

Stream API Sorting

Java Streams provide a functional approach.


Sorting Map Entries Using Streams

Example:

Map<String,Integer> sorted =
        map.entrySet()

        .stream()

        .sorted(
            Map.Entry
            .comparingByValue()
        )

        .collect(
            Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (a,b) -> a,
                LinkedHashMap::new
            )
        );

Why LinkedHashMap?

Collectors need a Map implementation.

Default:

HashMap

does not maintain sorting order.


Using:

LinkedHashMap::new

preserves:

Sorted insertion order

Stream Descending Sort

Map<String,Integer> sorted =
        map.entrySet()

        .stream()

        .sorted(
            Map.Entry
            .comparingByValue()
            .reversed()
        )

        .collect(
            Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (a,b)->a,
                LinkedHashMap::new
            )
        );

Collectors.toMap() Explained

Syntax:

Collectors.toMap(
    keyMapper,
    valueMapper,
    mergeFunction,
    mapSupplier
)

Example:

Collectors.toMap(

Map.Entry::getKey,

Map.Entry::getValue,

(a,b)->a,

LinkedHashMap::new

)

Meaning:

Key

Map.Entry::getKey

Take map key.


Value

Map.Entry::getValue

Take map value.


Merge Function

(a,b)->a

Handles duplicate keys.


Map Supplier

LinkedHashMap::new

Maintains order.


Sorting Map with Custom Object Values

Maps can contain objects as values.

Example:

Employee ID → Employee

Employee:

101 → John 90000

102 → Alice 120000

103 → Bob 75000

Sort by employee salary.


Comparator With Object Value

employees.entrySet()

.stream()

.sorted(
    Comparator.comparing(
        entry ->
        entry.getValue()
             .getSalary()
    )
)

.collect(
    Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue,
        (a,b)->a,
        LinkedHashMap::new
    )
);

Frequency Map Sorting

A very common interview pattern:

Word → Frequency

Example:

Input:

java spring java boot java

Frequency:

java=3

spring=1

boot=1

Sort by frequency:

java=3

spring=1

boot=1

Used in:

  • Top K frequent words
  • Log analysis
  • Analytics systems

Top K Frequent Elements Pattern

Interview question:

Find top K most frequent elements.


Example:

Input:

[1,1,1,2,2,3]

Frequency:

1 → 3

2 → 2

3 → 1

Top 2:

[1,2]

Approach:

Array

↓

HashMap Frequency

↓

Sort By Value

↓

Pick K

HashMap vs TreeMap vs LinkedHashMap

Feature HashMap LinkedHashMap TreeMap
Key Order No Insertion Sorted
Value Sorting No No No
Lookup O(1) O(1) O(log n)
Internal Structure Hash Table Hash + Linked List Red Black Tree
Use Case Fast lookup Maintain order Sorted keys

Important Concept

TreeMap sorts:

Keys

not:

Values

Example:

TreeMap:

Boot=1

Java=5

Spring=3

Sorted by:

Key

To sort by value:

Need:

Entry List + Comparator

Comparable vs Comparator

Comparable

Used when object has natural ordering.

Example:

Employee salary ascending

Inside class:

compareTo()

Comparator

Used for custom sorting.

Example:

Sort Map entries by value

Method:

compare()

Primitive vs Object Collections

Java Collections require objects.

Cannot:

HashMap<int,int>

Use:

HashMap<Integer,Integer>

Autoboxing:

int

↓

Integer

Common Interview Mistakes

Mistake 1

Trying to sort HashMap directly.

Wrong:

Collections.sort(map);

Correct:

Convert:

Map

↓

Entry List

↓

Sort

Mistake 2

Forgetting LinkedHashMap.

Problem:

Sorted entries lose order after collection.


Mistake 3

Confusing key sorting and value sorting.

Remember:

TreeMap → Key sorting

Comparator → Value sorting

Mistake 4

Using wrong comparator direction.

Ascending:

comparingByValue()

Descending:

comparingByValue()
.reversed()

Edge Cases

Case Handling
Empty Map Return empty map
Single entry Already sorted
Duplicate values Maintain stable order
Null values Handle separately
Large Map Avoid unnecessary copies

Interview Follow-up Questions

Q1. Sort HashMap by value.

Q2. Sort HashMap by key.

Q3. Find top K frequent elements.

Q4. Sort frequency map.

Q5. Difference between TreeMap and HashMap.

Q6. Preserve sorted order after sorting.

Q7. Sort Map values using Streams.

Q8. Sort Map with custom object values.


Related Java Collection Problems

  • Count Word Frequency Using HashMap
  • Sort Employees by Salary
  • Group Employees by Department
  • Remove Duplicate Objects
  • Find Duplicate Elements Using Set
  • Top K Frequent Elements
  • First Non-Repeating Character

Key Takeaways

Sorting a Map by value follows this pattern:

Map

 ↓

entrySet()

 ↓

List<Entry>

 ↓

Comparator

 ↓

LinkedHashMap

Recommended approaches:

Traditional Approach

Map.Entry + Comparator

Modern Java Approach

Stream API

+

Collectors.toMap()

Complexity:

For:

n map entries

Sorting:

O(n log n)

Space:

O(n)

Frequently Asked Interview Questions

Q1. Why can't HashMap sort values?

HashMap does not maintain ordering.


Q2. How do you sort by values?

Convert entries to a list and use Comparator.


Q3. Why use LinkedHashMap after sorting?

To preserve sorted insertion order.


Q4. Does TreeMap sort values?

No.

TreeMap sorts keys only.


Interview Tip

When asked:

"Sort a Map by value in Java."

Explain:

  1. Convert Map entries using entrySet().
  2. Sort entries using Comparator.
  3. Store result in LinkedHashMap.
  4. For Java 8+, use Stream API.
  5. Discuss ascending/descending and duplicate values.

For senior Java interviews, discuss:

  • HashMap internals.
  • Comparator design.
  • LinkedHashMap ordering.
  • Stream collectors.
  • Top K frequency patterns.

This demonstrates strong understanding of Java Collections, sorting algorithms, and real-world data processing.