Home  >  Article  >  Java  >  How to Sort a Java HashMap by Values in Ascending and Descending Order?

How to Sort a Java HashMap by Values in Ascending and Descending Order?

Susan Sarandon
Susan SarandonOriginal
2024-11-26 17:38:15582browse

How to Sort a Java HashMap by Values in Ascending and Descending Order?

Sorting a HashMap by Values

In Java, the HashMap data structure provides a convenient way to store key-value pairs. However, if you need to access the data based on the values associated with the keys, sorting the HashMap by values is necessary.

Sorting a HashMap in Ascending Order

One approach to sorting a HashMap by values is to use a Java 8 stream. The following code snippet demonstrates how to do this in ascending order:

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class SortHashMapByValues {

    public static void main(String[] args) {
        // Create an unsorted HashMap
        HashMap<Integer, String> unsortedMap = new HashMap<>();
        unsortedMap.put(1, "froyo");
        unsortedMap.put(2, "abby");
        unsortedMap.put(3, "denver");
        unsortedMap.put(4, "frost");
        unsortedMap.put(5, "daisy");

        // Sort the HashMap by values in ascending order
        Map<Integer, String> sortedMapAsc = unsortedMap.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));

        // Key, Value : 2, abby
        // Key, Value : 5, daisy
        // Key, Value : 3, denver
        // Key, Value : 4, frost
        // Key, Value : 1, froyo
        System.out.println(sortedMapAsc);
    }
}

Sorting a HashMap in Descending Order

To sort a HashMap by values in descending order, slightly modify the code snippet above:

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class SortHashMapByValues {

    public static void main(String[] args) {
        // Create an unsorted HashMap
        HashMap<Integer, String> unsortedMap = new HashMap<>();
        unsortedMap.put(1, "froyo");
        unsortedMap.put(2, "abby");
        unsortedMap.put(3, "denver");
        unsortedMap.put(4, "frost");
        unsortedMap.put(5, "daisy");

        // Sort the HashMap by values in descending order
        Map<Integer, String> sortedMapDesc = unsortedMap.entrySet()
                .stream()
                .sorted(Map.Entry.<Integer, String>comparingByValue().reversed())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));

        // Key, Value : 1, froyo
        // Key, Value : 4, frost
        // Key, Value : 3, denver
        // Key, Value : 5, daisy
        // Key, Value : 2, abby
        System.out.println(sortedMapDesc);
    }
}

This code will output the sorted HashMap with keys representing the original keys and values sorted in descending order. Both the ascending and descending order examples use a LinkedHashMap to maintain insertion order, ensuring that the keys are properly associated with the sorted values.

The above is the detailed content of How to Sort a Java HashMap by Values in Ascending and Descending Order?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn