Home > Java > javaTutorial > How to Sort a HashMap with ArrayList Values in Java?

How to Sort a HashMap with ArrayList Values in Java?

DDD
Release: 2024-11-28 00:26:11
Original
144 people have browsed it

How to Sort a HashMap with ArrayList Values in Java?

How to Sort a HashMap in Java

The provided HashMap is a mapping between keys and ArrayLists. To sort this structure, we have two options: using a TreeMap or writing custom code for sorting by ArrayList values.

Option 1: Using a TreeMap

If the need for a Map interface is not essential, consider using a TreeMap instead. A TreeMap maintains natural ordering among its keys, providing sorted access to key-value pairs.

Option 2: Custom Sorting by ArrayList Values

To sort the HashMap based on ArrayList values, you can use the following code:

// HashMap to be sorted
Map<String, ArrayList<Integer>> unsortedMap = new HashMap<>();

// Create a list to store the sorted values
List<Integer> sortedValues = new ArrayList<>();

// Iterate over the HashMap values and extract the ArrayLists
for (Map.Entry<String, ArrayList<Integer>> entry : unsortedMap.entrySet()) {
    sortedValues.addAll(entry.getValue());
}

// Sort the values in ascending order
Collections.sort(sortedValues);

// Create a new HashMap with the sorted values
Map<String, ArrayList<Integer>> sortedMap = new HashMap<>();
for (Map.Entry<String, ArrayList<Integer>> entry : unsortedMap.entrySet()) {
    sortedMap.put(entry.getKey(), new ArrayList<>( // Sorted list
        sortedValues.subList(0, entry.getValue().size())));
    sortedValues.subList(0, entry.getValue().size()).clear();
}
Copy after login

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template