Sorting HashMap by values

To sort a HashMap by values in Java, you can use the Map.Entry interface and the Comparator interface to create a comparator that compares the values in the map.

Here's an example of how you can sort a HashMap by values in Java:

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Main {
  public static void main(String[] args) {
    Map<String, Integer> map = new HashMap<>();
    map.put("A", 5);
    map.put("B", 1);
    map.put("C", 3);
    map.put("D", 2);
    map.put("E", 4);

    // sort the map by values
    Map<String, Integer> sortedMap = sortByValues(map);

    // print the sorted map
    for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) {
      System.out.println(entry.getKey() + ": " + entry.getValue());

  private static Map<String, Integer> sortByValues(Map<String, Integer> map) {
    // create a list of map entries
    List<Map.Entry<String, Integer>> list = new LinkedList<>(map.entrySet());

    // sort the list by values
    Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
      public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
        return o1.getValue().compareTo(o2.getValue());

    // create a new map to hold the sorted entries
    Map<String, Integer> sortedMap = new LinkedHashMap<>();

    // add the sorted entries to the new map
    for (Map.Entry<String, Integer> entry : list) {
      sortedMap.put(entry.getKey(), entry.getValue());

    return sortedMap;

This code defines a sortByValues method that takes a HashMap as an argument and returns a new LinkedHashMap with the entries sorted by values.

To sort the map by values, the sortByValues method first creates a list of Map.Entry objects from the map using the entrySet method. It then sorts the list using the Collections.sort method and a custom Comparator that compares the values in the Map.Entry objects.