# TreeMap sort by values in java

Let’s learn TreeMap sort by values in java.

## TreeMap sort by values in java

TreeMap stores key-value pairs which are in sorted order based on key. To sort a treemap by value we have to build some logic using comparator class. Here’s an example on how to sort a treemap by value.

```import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class TreeMapByValue
{
public static <K, V extends Comparable<V>> Map<K, V> sortValues(final Map<K, V> m)
{
Comparator<K> com = new Comparator<K>()
{
public int compare(K k1, K k2)
{
int compare = m.get(k1).compareTo(m.get(k2));
if(compare == 0)
{
return 1;
}
else
{
return compare;
}
}
};
Map<K, V> sortedByValues = new TreeMap<K, V>(com);
sortedByValues.putAll(m);
return sortedByValues;
}
public static void main(String[] args)
{
TreeMap<String, String> fruits = new TreeMap<String, String>();
fruits.put("K1", "Jackfruit");
fruits.put("K2", "Raspberry");
fruits.put("K3", "Kiwifruit");
fruits.put("K4", "Tangerine");
fruits.put("K5", "Strawberry");
// calling sortvalues method
Map<String, String> sortedMap = sortValues(fruits);
Set set = sortedMap.entrySet();
Iterator iterate = set.iterator();
// print elements
while(iterate.hasNext())
{
Map.Entry ma = (Map.Entry)iterate.next();
System.out.print(ma.getKey() + ": ");
System.out.println(ma.getValue());
}
}
}
```

Output:

K1: Jackfruit
K3: Kiwifruit
K2: Raspberry
K5: Strawberry
K4: Tangerine

Also read – major features of java