Automatically sorted by values map in Java

sort hashmap by value java 8
java sort map by value
how to sort employee object in hashmap
sort list of hashmap by value in java
sort map by value c++ geeksforgeeks
sort hashmap by value and then by key
sort map by value java geeksforgeeks
java value sort

I need to have an automatically sorted-by-values map in Java - so that It keeps being sorted at any time while I'm adding new key-value pairs or update the value of an existing key-value pair, or even delete some entry.

Please also have in mind that this map is going to be really big (100's of thousands, or even 10's of millions of entries in size).

So basically I'm looking for the following functionality:

Supposed that we had a class 'SortedByValuesMap' that implements the aforementioned functionality and we have the following code:

SortedByValuesMap<String,Long> sorted_map = new SortedByValuesMap<String, Long>();
sorted_map.put("apples", 4);
sorted_map.put("oranges", 2);
sorted_map.put("bananas", 1);
sorted_map.put("lemons", 3);
sorted_map.put("bananas", 6);

for (String key : sorted_map.keySet()) {
  System.out.println(key + ":" + sorted_map.get(key));

the output should be:


In particular, what's really important for me, is to be able to get the entry with the lowest value at any time - using a command like:

smallestItem = sorted_map.lastEntry();

which should give me the 'oranges' entry

EDIT: I am a Java newbie so please elaborate a bit in your answers - thanks

EDIT2: This might help: I am using this for counting words (for those who are familiar: n-grams in particular) in huge text files. So I need to build a map where keys are words and values are the frequencies of those words. However, due to limitations (like RAM), I want to keep only the X most frequent words - but you can't know beforehand which are going to be the most frequent words of course. So, the way I thought it might work (as an approximation) is to start counting words and when the map reaches a top-limit (like 1 mil entries) , the least frequent entry will be deleted so as to keep the map's size to 1 mil always.

Sorting a Hashmap according to values, import java.lang.*;. public class GFG {. // function to sort hashmap by values. public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm). Simple quick to use examples to sort Map by values, using Java 8 Stream APIs, in ascending and descending (reverse) orders.. In the center of logic is the method Map.Entry.comparingByValue() which compares Map.Entry in natural order on value.

How about using additional index or only TreeMap<Long, TreeSet<String>> or TreeMap<Long, String> if Long values are distinct?

You can also write a Heap.

Sorting a HashMap according to keys in Java, import java.util.*;. class sortmapKey {. // This map stores unsorted values. static Map<String, Integer> map = new HashMap<>();. // Function to sort map by Key. In this tutorial, we demonstrate how to sort a Map by value in Java, using methods like the LinkedHashMap, Comparator, and Sorted to provide example code.

Guava BiMap Solution:

//Prepare original data
BiMap<String, Integer> biMap = HashBiMap.create();
biMap.put("apples" , 4);
biMap.put("oranges", 2);
biMap.put("bananas", 1);
biMap.put("lemons" , 3);
biMap.put("bananas", 6);

//Create a desc order SortedMap
SortedMap<Integer, String> sortedMap = new TreeMap<Integer, String>(new Comparator<Integer>(){
    @Override public int compare(Integer o1, Integer o2) {
      return o2-o1;

//Put inversed map
for (Map.Entry<Integer, String> e: sortedMap.entrySet()) {

How to sort a TreeMap by value in java, A TreeMap is always sorted based on its keys, however if you want to sort it based on its values then you can build a logic to do this using comparator. In Java, we can use the TreeMap class to sort a map by its keys. This class is very handy to use. However, sometimes we need to sort a map by its values. How to sort a map by its values is a most frequently asked question by Java programmers. In this post, I will develop the best way to write such a method. The following is a solution to sort a

Try the solution posted on . You have the flexibility of doing sorting ascending or descending too.

Here is what they say

import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class MapValueSort {

    /** inner class to do soring of the map **/
    private static class ValueComparer implements Comparator<String> {
        private Map<String, String>  _data = null;
        public ValueComparer (Map<String, String> data){
            _data = data;

         public int compare(String o1, String o2) {
             String e1 = (String) _data.get(o1);
             String e2 = (String) _data.get(o2);
             return e1.compareTo(e2);

    public static void main(String[] args){

        Map<String, String> unsortedData = new HashMap<String, String>();
        unsortedData.put("2", "DEF");
        unsortedData.put("1", "ABC");
        unsortedData.put("4", "ZXY");
        unsortedData.put("3", "BCD");

        SortedMap<String, String> sortedData = new TreeMap<String, String>(new MapValueSort.ValueComparer(unsortedData));



    private static void printMap(Map<String, String> data) {
        for (Iterator<String> iter = data.keySet().iterator(); iter.hasNext();) {
            String key = (String);





SortedMap (Java Platform SE 8 ), This order is reflected when iterating over the sorted map's collection views (​returned by the entrySet , keySet and values methods). Several additional operations  How to sort Map by Key or Value in Java 8. A Map can also be sorted with stream.sorted() method in Java 8. We can sort the Map based on its Keys or Values.

Update: You cannot sort maps by values, sorry.

You can use SortedMap implementation like TreeMap with Comparator defining order by values (instead of default - by keys).

Or, even better, you can put elements into a PriorityQueue with predefined comparator by values. It should be faster and take less memory compared to TreeMap.

How to sort a Map in Java –, Few Java examples to sort a Map by its keys or values. Note If you are 1.1 Uses java.util.TreeMap , it will sort the Map by keys automatically. Blog Java and J2EE Tutorials In Java How to Sort a Map on the Values? The Map Interface – Jav In Java How to sort a Map on Value? There are number of ways. Here we will follow below steps. An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at-most one value. HashMap to ArrayList?

Java HashMap sort by Values Example, If you want to sort HashMap by key, you can use the implementation of SortedMap like TreeMap, which will automatically sort the Map by keys. If you want to sort HashMap by key, you can use the implementation of SortedMap like TreeMap, which will automatically sort the Map by keys. Sorting HashMap by values will need a collection that maintains order like LinkedHashMap. a) Sorting HashMap by value if you want only values

Java sort Map by key (ascending and descending orders), Sort Map by Key using TreeMap. In ascending order. By default, all key-value pairs in TreeMap are sorted in their natural order. So all you need to do is add all​  4. Sort a Map. A map is the collection of key-value pairs. So map can be sorted in two ways i.e. sort by key or sort by value. 4.1. Sort a Map by Key. The best and most effective a sort a map by keys is to add all map entries in TreeMap object. TreeMap store the entry sets in sorted order by keys.

Why is it sorting my HashMap automatically. I don't want that , Hashmap, by definition, is an un-ordered list of key-value items. re: Also, why is it that when I import java.util.HashMap instead of the entire java. A Map that further provides a total ordering on its keys. The map is ordered according to the natural ordering of its keys, or by a Comparator typically provided at sorted map creation time. This order is reflected when iterating over the sorted map's collection views (returned by the entrySet, keySet and values methods).

  • millions of entries? why not use a database for that?
  • What if there were two keys with identical lowest-values? What should be the expected behaviour of lastEntry()? (E.G. another entry of limes -> 2 was in the map)
  • @Kru: a database would make it really slow
  • If this is just english, you're over-estimating how many words there are, particularly that are commonly used.
  • @Dave Newton you're right - I mentioned words so as not to confuse people who are unfamiliar with n-grams, which are what I am actually counting. N-grams, especially as N goes up, can become really diverse. The possible combinations go up exponentially.
  • Long values are not distinct. Two different entries might have the same Long values - Long values actually represent frequencies
  • So you can use TreeMap<Long, TreeSet<String>>.
  • that might work but I'm afraid it would double the amount of time since we're doubling the map operations - and in my case, where I have millions of entries that might make a huge difference
  • Not that much. Just constant factor will slightly rise. You can also create some pair class like Map.Entry<K,V> and use TreeSet<Pair<Long, String>>.
  • Yes, but you can keep both TreeMap<Long,TreeSet<String>> and Map<String,Long>. I guess there is no provided single data structure in java that do both tricks. In SQL table you would want to have indexes on two columns, so I guess you also need 2 "indexes" in java.