Value Sort Map Utility (Java Code)
Submitted By:
nirajagarwal
Rating:





(
Rate It)
Share:
By Email
This class is used to show how you can sort a java.uti.Map for values. This also takes care of null and duplicate values present in the map. Many times we come accross the requirement where we need to sort a Map (HashMap, Hashtable) for it's values. Like User Id's as key and User Name as values; and need to sort it with User Names. This can be good fit for such scenarios.
File Details
NOTE: Some downloads must be obtained through publishers´s site.
Do you want to get your software listed on this site? Go to our
submissions area.
Screenshot
Details
Number of downloads:
1069
Comments (6)
Comment
Posted by: anil on Friday, June 22, 2007
it is not working when i give numbers as values. its not sorting..but good for the strings
sortByValue(Map map)
Posted by: traveler_82@poczta.onet.pl on Tuesday, July 03, 2007
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());
}
});
// logger.info(list);
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;
}
Near to Average Rating




Posted by: Sajeel Shuakat on Thursday, April 02, 2009
With soorry, i think if its not veryefficient coding.
Good! useful!!




Posted by: shyam on Wednesday, August 12, 2009
sorted map by values improved




Posted by: jessifb88 on Thursday, January 14, 2010
This code is very good but the way to sort a map in this code can't order correctly values with characters like áéí... or other. The way to resolve this is:
Map<String,String> sortByValue(Map<String,String> map) {
List<String> list = new LinkedList(map.entrySet());
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) cleanComparison((((Map.Entry) (o1)).getValue()).toString()))
.compareTo(cleanComparison((((Map.Entry) (o2)).getValue()).toString()));
}
});
Map<String, String> result = new LinkedHashMap<String, String>();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
result.put((String)entry.getKey(), (String)entry.getValue());
}
return result;
}
String cleanComparison(String s) {
String result = s.toLowerCase();
String[] or = {"á","é","í","ó","ú","ä","ë","ï","ö","ü","à","è","ì","ò","ù"};
String[] res = {"a","e","i","o","u","a","e","i","o","u","a","e","i","o","u"};
for (int i = 0; i < or.length; i++) {
result = result.replace(or[i], res[i]);
}
return result;
}
The only online solution which worked for me :)




Posted by: Maha on Tuesday, January 04, 2011
So simple and yet portable :D Thanks alot, saved me alot of time!
Add Your Rating