Tuesday, December 2, 2014
Sort HashMap on Value
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class MapSortByValue {
public static void main(String[] args){
Map map = new HashMap();
map.put("a", 1);
map.put("c", 3);
map.put("b", 2);
Set set = map.entrySet();
List list = new ArrayList(set); // convert set to list
// before sorting
for (int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
Collections.sort(list, new Comparator(){
@Override
public int compare(Object o1, Object o2) {
Map.Entry<String, Integer> entry1 = (Map.Entry<String, Integer>) o1;
Map.Entry<String, Integer> entry2 = (Map.Entry<String, Integer>) o2;
return (entry1.getValue()).compareTo(entry2.getValue());
}
});
// after sorting
for (int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment