---
title: "How to sort a Map<Key, Value> on the values in Java?"  
description: "How to sort a Map<Key, Value> on the values in Java?"  
author: "Anonymous User"  
published: 2015-05-13  
updated: 2015-05-14  
canonical: https://www.mindstick.com/forum/23222/how-to-sort-a-map-key-value-on-the-values-in-java  
category: "java"  
tags: ["java", "collection"]  
reading_time: 1 minute  

---

# How to sort a Map<Key, Value> on the values in Java?

I am relatively new to [Java](https://www.mindstick.com/articles/12214/web-development-company-in-india-laid-on-the-foundation-of-concrete-java-programming), and [often](https://answers.mindstick.com/qa/115859/how-do-i-resolve-the-we-limit-how-often-you-can-do-certain-things-error) find that I need to sort a [Map](https://yourviews.mindstick.com/view/81351/nepal-parliament-s-approves-new-controversial-map-india-rejects-it-but)<Key, [Value](https://www.mindstick.com/articles/23219/an-optimized-description-adds-value-to-experience-and-in-turn-effectively-guest-posting-packages)> on the [values](https://www.mindstick.com/forum/327/sum-textbox-values). Since the values are not [unique](https://www.mindstick.com/blog/12870/how-to-be-unique-in-business), I find myself converting the keySet into an [array](https://www.mindstick.com/articles/335/jagged-array-in-c-sharp-dot-net), and [sorting](https://www.mindstick.com/articles/1581/sorting-list-with-side-bar) that array through array sort with a [custom](https://www.mindstick.com/blog/12298/use-custom-writing-services-to-get-through-the-finals) comparator that sorts on the value associated with the key. Is there an easier way?\

## Replies

### Reply by Anonymous User

```
static Map sortByValue(Map map) {     List list = new LinkedList(map.entrySet());     Collections.sort(list, new Comparator() {          public int compare(Object o1, Object o2) {               return ((Comparable) ((Map.Entry) (o1)).getValue())              .compareTo(((Map.Entry) (o2)).getValue());          }     });    Map result = new LinkedHashMap();    for (Iterator it = list.iterator(); it.hasNext();) {        Map.Entry entry = (Map.Entry)it.next();        result.put(entry.getKey(), entry.getValue());    }    return result;}  
```


---

Original Source: https://www.mindstick.com/forum/23222/how-to-sort-a-map-key-value-on-the-values-in-java

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
