Algorithm


  1. Create a Map:

    • Initialize a Map with the desired key-value pairs.
  2. Convert Map to List:

    • Create a List of Map.Entry objects by using the entrySet() method of the Map.
  3. Sort the List:

    • Implement a custom comparator to sort the list based on the values of the Map.Entry objects.
    • You can use the Collections.sort() method and provide the custom comparator.
  4. Create a Sorted Map:

    • Create a new LinkedHashMap to store the sorted entries.
  5. Populate Sorted Map:

    • Iterate through the sorted list and add each Map.Entry to the new LinkedHashMap.
  6. Display or Use the Sorted Map:

    • The new LinkedHashMap now contains entries sorted by values.

 

Code Examples

#1 Code Example- Java Programing Sort a map by values

Code - Java Programming

import java.util.*;
import java.util.Map.Entry;

class Main {

  public static void main(String[] args) {

    // create a map and store elements to it
    LinkedHashMap < String, String> capitals = new LinkedHashMap();
    capitals.put("Nepal", "Kathmandu");
    capitals.put("India", "New Delhi");
    capitals.put("United States", "Washington");
    capitals.put("England", "London");
    capitals.put("Australia", "Canberra");

    // call the sortMap() method to sort the map
    Map < String, String> result = sortMap(capitals);

    for (Map.Entry entry : result.entrySet()) {
      System.out.print("Key: " + entry.getKey());
      System.out.println(" Value: " + entry.getValue());
    }
  }

  public static LinkedHashMap sortMap(LinkedHashMap map) {
    List  < Entry(map.entrySet());

    // call the sort() method of Collections
    Collections.sort(capitalList, (l1, l2) -> l1.getValue().compareTo(l2.getValue()));

    // create a new map
    LinkedHashMap < String, String> result = new LinkedHashMap();

    // get entry from list to the map
    for (Map.Entry entry : capitalList) {
      result.put(entry.getKey(), entry.getValue());
    }

    return result;
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Key: Australia Value: Canberra
Key: Nepal Value: Kathmandu
Key: England Value: London
Key: India Value: New Delhi
Key: United States Value: Washington
Advertisements

Demonstration


Java Programing Example to Sort a Map By Values-DevsEnv