2

I need to sort my HashMap according to the values stored in it. The HashMap contains the business name as keys and difference of latitude and longitude as values

hashMapLocationDifference = new HashMap<String, Double>();

Menu
  • 677
  • 1
  • 12
  • 30
  • HashMap has no knowledge of the concept of order. You need another type of Collection – Blackbelt Jun 01 '15 at 12:31
  • which type of collection?? @Blackbelt – Menu Jun 01 '15 at 12:36
  • For sorting purpose use List instead of Map. – Anand Singh Jun 01 '15 at 12:37
  • Okay but I want to sort data based on keys and values so how to use list instead of Map??? @AnandSingh – Menu Jun 01 '15 at 12:44
  • See this thread please: http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java and this article: http://java67.blogspot.in/2015/01/how-to-sort-hashmap-in-java-based-on.html – Anand Singh Jun 01 '15 at 12:54
  • How a bout a TreeMap? It orders entries based on key ordering (take a look at this http://beginnersbook.com/2013/12/treemap-in-java-with-example/). – Edson Menegatti Jun 01 '15 at 14:25

1 Answers1

0

Assuming Java ,you could sort HashMap just like this :

public LinkedHashMap sortHashMapByValuesD(HashMap passedMap) {
   List mapKeys = new ArrayList(passedMap.keySet());
   List mapValues = new ArrayList(passedMap.values());
   Collections.sort(mapValues);
   Collections.sort(mapKeys);

   LinkedHashMap sortedMap = new LinkedHashMap();

   Iterator valueIt = mapValues.iterator();
   while (valueIt.hasNext()) {
       Object val = valueIt.next();
       Iterator keyIt = mapKeys.iterator();

       while (keyIt.hasNext()) {
           Object key = keyIt.next();
           String comp1 = passedMap.get(key).toString();
           String comp2 = val.toString();

           if (comp1.equals(comp2)){
               passedMap.remove(key);
               mapKeys.remove(key);
               sortedMap.put((String)key, (Double)val);
               break;
           }

       }

   }
   return sortedMap;
}
Kartheek
  • 7,104
  • 3
  • 30
  • 44