Monday, January 20, 2025
HomeProgrammingHow To Sort A HashMap In Java

How To Sort A HashMap In Java

To sort a HashMap in Java, you need to consider that a HashMap does not maintain any order of its keys or values. If you want to sort the HashMap by keys or by values, you need to use additional collections such as TreeMap (for sorting by keys) or use Stream and Comparator for sorting by values.

Here’s how you can sort a HashMap in Java:

1. Sort by Keys using TreeMap

A TreeMap is a sorted map that automatically sorts its keys in natural order or according to a specified comparator.

Example: Sort by Keys

import java.util.*;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("Banana", 3);
        hashMap.put("Apple", 2);
        hashMap.put("Orange", 5);
        
        // Sort the HashMap by keys using a TreeMap
        TreeMap<String, Integer> sortedMap = new TreeMap<>(hashMap);
        
        // Print the sorted map
        System.out.println("Sorted by keys: " + sortedMap);
    }
}

Output:

Sorted by keys: {Apple=2, Banana=3, Orange=5}

In this example, the TreeMap automatically sorts the keys in natural order (alphabetically, in this case).

See also  CSS: Background Image on Background Color

2. Sort by Values using Streams

If you want to sort the HashMap by values, you can use Java Streams to sort the entries by their values. This is a more flexible approach when you need to sort the map based on non-key properties.

Example: Sort by Values

import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("Banana", 3);
        hashMap.put("Apple", 2);
        hashMap.put("Orange", 5);
        
        // Sort the HashMap by values using Streams
        List<Map.Entry<String, Integer>> sortedList = hashMap.entrySet()
            .stream()
            .sorted(Map.Entry.comparingByValue())  // Sort by values
            .collect(Collectors.toList());
        
        // Print the sorted entries
        System.out.println("Sorted by values:");
        for (Map.Entry<String, Integer> entry : sortedList) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}

Output:

Sorted by values:
Apple = 2
Banana = 3
Orange = 5

3. Sort by Values in Reverse Order

You can also sort the map by values in reverse order by using a custom comparator.

See also  How to calculate percentage with a SQL statement

Example: Sort by Values in Reverse Order

import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("Banana", 3);
        hashMap.put("Apple", 2);
        hashMap.put("Orange", 5);
        
        // Sort the HashMap by values in reverse order
        List<Map.Entry<String, Integer>> sortedList = hashMap.entrySet()
            .stream()
            .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())  // Reverse sorting
            .collect(Collectors.toList());
        
        // Print the sorted entries
        System.out.println("Sorted by values (descending order):");
        for (Map.Entry<String, Integer> entry : sortedList) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}

Output:

Sorted by values (descending order):
Orange = 5
Banana = 3
Apple = 2

4. Custom Sorting by Values

If you need a custom sorting order for the values (e.g., sorting by descending order of values), you can pass a custom comparator to the sorted() function in the stream.

Example: Custom Comparator for Sorting

import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("Banana", 3);
        hashMap.put("Apple", 2);
        hashMap.put("Orange", 5);
        
        // Sort the HashMap by values using a custom comparator
        List<Map.Entry<String, Integer>> sortedList = hashMap.entrySet()
            .stream()
            .sorted((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()))  // Custom comparator
            .collect(Collectors.toList());
        
        // Print the sorted entries
        System.out.println("Custom sorted by values:");
        for (Map.Entry<String, Integer> entry : sortedList) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}

Output:

Custom sorted by values:
Orange = 5
Banana = 3
Apple = 2

 

  • To sort by keys: Use TreeMap, which automatically sorts the keys in natural order.
  • To sort by values: Use Java Streams and Map.Entry.comparingByValue() to sort by values. You can also use custom comparators to sort in a specific order or reverse.
  • Custom Sorting: You can provide your own comparator to fine-tune how the entries are sorted by values.
See also  How do I refresh a page using JavaScript?-jquery

Using these techniques, you can sort a HashMap either by its keys or values in Java.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x