Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaJava Program to Sort a HashMap by Keys and Values

Java Program to Sort a HashMap by Keys and Values

HashMap<K, V> is a Java Collection and is a part of java.util package. It provides the basic implementation of the Map interface of Java. It stores the data in the form of Key, Value pairs, where the keys must be unique but there is no restriction for values. If we try to insert the duplicate key, it will replace the element of the corresponding key.

HashMap Sorting by Values

The idea is to store the entry set in a list and then sort the list based on values using the Collections.sort() method with the help of Comparator. Then fetch the value for each key from the list and then display the result.

Example

Java




// Java program to sort Hashmap based on values
 
import java.lang.*;
import java.util.*;
 
public class GFG {
 
    // function to sort hashmap based on values
    public static HashMap<String, Integer>
    sortByValue(HashMap<String, Integer> hm)
    {
        // Creating a list from elements of HashMap
        List<Map.Entry<String, Integer> > list
            = new LinkedList<Map.Entry<String, Integer> >(
                hm.entrySet());
 
        // Sorting the list using Collections.sort() method
        // using Comparator
        Collections.sort(
            list,
            new Comparator<Map.Entry<String, Integer> >() {
                public int compare(
                    Map.Entry<String, Integer> object1,
                    Map.Entry<String, Integer> object2)
                {
                    return (object1.getValue())
                        .compareTo(object2.getValue());
                }
            });
 
        // putting the  data from sorted list back to hashmap
        HashMap<String, Integer> result
            = new LinkedHashMap<String, Integer>();
        for (Map.Entry<String, Integer> me : list) {
            result.put(me.getKey(), me.getValue());
        }
 
        // returning the sorted HashMap
        return result;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // creating object of HashMap class
        HashMap<String, Integer> hashmap
            = new HashMap<String, Integer>();
 
        // inserting key-value pair into hashmap
        hashmap.put("five", 5);
        hashmap.put("seven", 7);
        hashmap.put("three", 3);
        hashmap.put("nine", 9);
        hashmap.put("zero", 0);
        hashmap.put("eight", 8);
 
        // sorting the HashMap based on values
        Map<String, Integer> map = sortByValue(hashmap);
 
        // print the sorted hashmap(based on values)
        for (Map.Entry<String, Integer> entry :
             map.entrySet()) {
            System.out.println("Key : " + entry.getKey()
                               + ", Value : "
                               + entry.getValue());
        }
    }
}


 
 

Output

Key : zero, Value : 0
Key : three, Value : 3
Key : five, Value : 5
Key : seven, Value : 7
Key : eight, Value : 8
Key : nine, Value : 9

 

HashMap Sorting by Keys

 

The idea is to put all data of HashMap into an ArrayList.Then extract all the keys of HashMap into an ArrayList. Next, sort the extracted keys using the Collections.sort() method, and then for each key extract its value using the get() method. Finally, the map is sorted according to its keys.

 

Example

 

Java




// Java Code to sort Map by key value
import java.util.*;
class GFG {
 
    // This map stores unsorted values
    static HashMap<Integer, String> m = new HashMap<>();
 
    // Function to sort map by Key
    public static void sortMapByKey()
    {
        ArrayList<Integer> sortKeys
            = new ArrayList<Integer>(m.keySet());
 
        Collections.sort(sortKeys);
 
        // Getting value for each key and displaying
        // results.
        for (Integer x : sortKeys)
            System.out.println("Key = " + x
                               + ", Value = " + m.get(x));
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // putting values in the Map
        m.put(7, "seven");
        m.put(5, "five");
        m.put(1, "one");
        m.put(3, "three");
        m.put(9, "nine");
 
        // Calling the function to sortMapByKey to
        // perform sorting based on keys
        sortMapByKey();
    }
}


 
 

Output

Key = 1, Value = one
Key = 3, Value = three
Key = 5, Value = five
Key = 7, Value = seven
Key = 9, Value = nine

 

RELATED ARTICLES

Most Popular

Recent Comments