Sort a Map<Key, Value> by values in java

Sort a Map<Key, Value> by values in java

To sort a Map<Key, Value> by its values in Java, you can follow these steps:

  1. Convert the Map to a list of Map.Entry objects.
  2. Use a custom comparator to sort the list based on the values.
  3. Create a new LinkedHashMap and populate it with the sorted entries.

Here's an example of how to do this:

import java.util.*; public class SortMapByValues { public static <K, V extends Comparable<? super V>> Map<K, V> sortByValues(Map<K, V> map) { List<Map.Entry<K, V>> entryList = new ArrayList<>(map.entrySet()); Collections.sort(entryList, new Comparator<Map.Entry<K, V>>() { @Override public int compare(Map.Entry<K, V> entry1, Map.Entry<K, V> entry2) { return entry1.getValue().compareTo(entry2.getValue()); } }); Map<K, V> sortedMap = new LinkedHashMap<>(); for (Map.Entry<K, V> entry : entryList) { sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; } public static void main(String[] args) { Map<String, Integer> unsortedMap = new HashMap<>(); unsortedMap.put("one", 1); unsortedMap.put("three", 3); unsortedMap.put("two", 2); unsortedMap.put("four", 4); Map<String, Integer> sortedMap = sortByValues(unsortedMap); for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } } 

In this example, the sortByValues method takes a Map as input and returns a new LinkedHashMap containing the entries sorted by their values in ascending order. You can modify the comparator to sort in descending order if needed.


More Tags

cosine-similarity nsuserdefaults multiple-select url-parameters micro-optimization database-administration file-read java.util.logging angular-material-datetimepicker collation

More Java Questions

More Everyday Utility Calculators

More Date and Time Calculators

More Statistics Calculators

More Housing Building Calculators