Comprehensive Guide to Sorting HashMap by Values in Java

Nov 13, 2025 · Programming · 10 views · 7.8

Keywords: Java | HashMap Sorting | Value Sorting | Algorithm Implementation | Collections Framework

Abstract: This article provides an in-depth exploration of various methods for sorting HashMap by values in Java. The focus is on the traditional approach using auxiliary lists, which maintains sort order by separating key-value pairs, sorting them individually, and reconstructing the mapping. The article explains the algorithm principles with O(n log n) time complexity and O(n) space complexity, supported by complete code examples. It also compares simplified implementations using Java 8 Stream API, helping developers choose the most suitable sorting solution based on project requirements.

Overview of HashMap Sorting Problem

In Java programming, HashMap is a commonly used key-value storage structure, but its internal implementation does not guarantee element order. When sorting by values is required, developers need to employ specific algorithms. This article is based on a concrete case: sorting a HashMap<Integer,String> storing contact names in ascending order by value (names).

Core Sorting Algorithm Principles

Since HashMap itself does not support value-based sorting, key-value pairs must be extracted into sortable data structures. The basic approach involves: first separating keys and values into different collections, sorting them individually, then reconstructing the mapping based on sorted values. This method has O(n log n) time complexity and O(n) space complexity, where n is the number of elements in the map.

Complete Implementation Code Analysis

The following complete implementation using auxiliary lists properly handles duplicate values:

import java.util.*;

public class HashMapSorter {
    
    public LinkedHashMap<Integer, String> sortHashMapByValues(
            HashMap<Integer, String> passedMap) {
        
        // Extract all keys and values into separate lists
        List<Integer> mapKeys = new ArrayList<>(passedMap.keySet());
        List<String> mapValues = new ArrayList<>(passedMap.values());
        
        // Sort values and keys separately
        Collections.sort(mapValues);
        Collections.sort(mapKeys);
        
        // Create LinkedHashMap to maintain insertion order
        LinkedHashMap<Integer, String> sortedMap = new LinkedHashMap<>();
        
        Iterator<String> valueIt = mapValues.iterator();
        while (valueIt.hasNext()) {
            String val = valueIt.next();
            Iterator<Integer> keyIt = mapKeys.iterator();
            
            while (keyIt.hasNext()) {
                Integer key = keyIt.next();
                String comp1 = passedMap.get(key);
                String comp2 = val;
                
                // Match corresponding key-value pairs
                if (comp1.equals(comp2)) {
                    keyIt.remove();
                    sortedMap.put(key, val);
                    break;
                }
            }
        }
        return sortedMap;
    }
    
    public static void main(String[] args) {
        HashMap<Integer, String> map = new HashMap<>();
        map.put(1, "froyo");
        map.put(2, "abby");
        map.put(3, "denver");
        map.put(4, "frost");
        map.put(5, "daisy");
        
        HashMapSorter sorter = new HashMapSorter();
        LinkedHashMap<Integer, String> sortedMap = sorter.sortHashMapByValues(map);
        
        // Output sorted results
        for (Map.Entry<Integer, String> entry : sortedMap.entrySet()) {
            System.out.println(entry.getKey() + "," + entry.getValue() + ";");
        }
    }
}

Detailed Algorithm Execution Process

The execution process of this algorithm can be divided into three main phases:

Data Extraction Phase: Obtain all keys and values separately using keySet() and values() methods, storing them in ArrayList. This separation ensures independence for subsequent sorting operations.

Sorting Processing Phase: Use Collections.sort() to naturally sort the value list (ascending order), while also sorting the key list. This dual sorting provides the foundation for subsequent matching process.

Mapping Reconstruction Phase: Traverse sorted values and keys through nested iterators, adding matched key-value pairs to LinkedHashMap. Using LinkedHashMap instead of regular HashMap maintains element insertion order, thus preserving the sorting result.

Advantages in Handling Duplicate Values

A significant advantage of this method is its ability to properly handle multiple keys with identical values. During the matching process, each value finds its corresponding original key, ensuring correct mapping relationships even when duplicate values exist. This approach is more robust than simple stream operations.

Java 8 Stream API Alternative

For developers using Java 8 and later versions, more concise stream operations can achieve the same functionality:

Map<Integer, String> sortedMap = map.entrySet().stream()
    .sorted(Map.Entry.comparingByValue())
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue,
        (e1, e2) -> e1,
        LinkedHashMap::new
    ));

This approach offers more concise code, but the traditional method provides better controllability when dealing with complex sorting logic or requiring special error handling.

Performance Analysis and Optimization Suggestions

Both methods have O(n log n) time complexity, primarily consumed by sorting operations. Space complexity is O(n) for storing temporary lists. In practical applications, if the map scale is large, consider the following optimization strategies:

Use more efficient sorting algorithms, consider parallel processing for large datasets, employ external sorting techniques in memory-constrained environments. For specific use cases, consider using ordered collections like TreeMap to avoid frequent sorting operations.

Practical Application Scenarios

Value-based HashMap sorting technology finds wide applications in multiple domains: contact list sorting, product price sorting, student grade ranking, log time sorting, etc. Understanding these implementation methods helps developers choose the most appropriate solutions when facing similar requirements.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.