java按照map的value排序
2015-09-02 15:30
381 查看
java按照map的value排序
分类: java2012-08-2620:37 4843人阅读 评论(0) 收藏 举报
javaintegeriteratorexceptionapplication算法
java的TreeMap可以排序,只可惜是按照key来排序的,或者重写其他Map的排序算法也都是按照key来排序的,下面贴出来一个按照value排序的算法:
[java] view
plaincopy
public class SortMap {
public static void main(String[] args) throws Exception {
// TODO code application logic here
Map<String, Integer> myMap = new LinkedHashMap();
myMap.put("1", 1);
myMap.put("2", 4);
myMap.put("3", 3);
myMap.put("4", 9);
myMap.put("5", 6);
myMap.put("6", 2);
printMap(myMap);
myMap = sortMap(myMap);
printMap(myMap);
}
private static void printMap(Map map){
System.out.println("===================mapStart==================");
Iterator it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry entry = (Map.Entry) it.next();
System.out.println(entry.getKey() + ":" + entry.getValue());
}
System.out.println("===================mapEnd==================");
}
public static Map sortMap(Map oldMap) {
ArrayList<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(oldMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Entry<java.lang.String, Integer> arg0,
Entry<java.lang.String, Integer> arg1) {
return arg0.getValue() - arg1.getValue();
}
});
Map newMap = new LinkedHashMap();
for (int i = 0; i < list.size(); i++) {
newMap.put(list.get(i).getKey(), list.get(i).getValue());
}
return newMap;
}
}
相关文章推荐
- priority_queue用法
- UIView与CALayer的区别
- Failed to instantiate the default view controller for UIMainStoryboardFile
- Using SVN as Source Control inside UE4
- UE4 异步资源加载
- easyui datagrid to excel
- 简述UIDatePicker的用法
- easyui 列表datagrid初始化两次的问题
- 8.11.2 Table Locking Issues 表锁发生
- 提高Interface Builder高效工作的8个技巧
- hdu3530 Subsequence(单调队列)
- UE4 Command-Line Arguments
- 从客户端中检测到有潜在危险的 Request.Form 值 方法
- timequest
- Xcode 根据要显示的内容和内容字体,自适应调整UILabel的大小
- UE4 Packaging and Cooking Games
- UE4 Patching
- UE4 Packaging Projects
- BW delta queue (RSA7): Questions and answers
- UE3 内容烘焙