Sort a HashMap based on Keys or Values
Sort based on keys is simple , just dump the map into TreeMap (TreeMap is sorted by nature)
Map myMap = new HashMap();
// put keys and values........
Map sortedMap = new TreeMap(myMap);
If you want to sort your HashMap based on values :
HashMap map1 = new HashMap();
map1.put("cat",5);
map1.put("cow",4);
map1.put("dog",3);
map1.put("horse",2);
List mpKeys = new ArrayList(map1.keySet());
List mpValues = new ArrayList(map1.values());
HashMap map = new LinkedHashMap();
TreeSet sortedSet = new TreeSet(mapValues);
Object[] sortedArray = sortedSet.toArray();
int size = sortedArray.length;
// descending
for (int i=size-1; i>=0; i--)
System.out.println(mpKeys.get(mpValues.indexOf(sortedArray[i]))+" "+sortedArray[i]);
Any discussions will be appreciated.
Map myMap = new HashMap();
// put keys and values........
Map sortedMap = new TreeMap(myMap);
If you want to sort your HashMap based on values :
HashMap map1 = new HashMap();
map1.put("cat",5);
map1.put("cow",4);
map1.put("dog",3);
map1.put("horse",2);
List mpKeys = new ArrayList(map1.keySet());
List mpValues = new ArrayList(map1.values());
HashMap map = new LinkedHashMap();
TreeSet sortedSet = new TreeSet(mapValues);
Object[] sortedArray = sortedSet.toArray();
int size = sortedArray.length;
// descending
for (int i=size-1; i>=0; i--)
System.out.println(mpKeys.get(mpValues.indexOf(sortedArray[i]))+" "+sortedArray[i]);
Any discussions will be appreciated.
Comments
Correction: Line 13 should read
TreeSet sortedSet = new TreeSet(mpValues);
instead of
TreeSet sortedSet = new TreeSet(mapValues);
__________________________________________
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
/**
*
* @author pavanj
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
HashMap callList = new HashMap();
callList.put("java", "pavan");
callList.put("makes", "srinivas");
callList.put("life", "sample");
callList.put("easy", "java");
Set set=callList.keySet();
String[] keys=new String[set.size()];
set.toArray(keys);
List tmpkeyList=Arrays.asList(keys);
Collections.sort(tmpkeyList);
for(String key:tmpkeyList){
System.out.println(key+":"+callList.get(key));
}
}
}
_________________________________
Thanks & Regards
-----------------
Pavan
(mpKeys.get(mpValues.indexOf(sortedArray[i]))
you will only return the first key with that value.
Make use of TreeMap instaed of HashMap it is sorted by default.
Or you can use
new TreeMap(hashMap);