java 对map中的 value 排序
2015-06-11 11:53
351 查看
package Map; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; public class SortMap { public static void main(String[] args) { Map map=new TreeMap (); map.put("图书" , 4); map.put("音像" , 6); map.put("素材" , 9); map.put("音乐" , 8); map.put("影视" , 7); map.put("动漫" , 4); map.put("歌曲" , 3); map.put("图片" , 2); map.put("图标" , 6); ArrayList<Map.Entry<String,Integer>> entries= sortMap(map); for( int i=0;i<5;i++){ System. out.print(entries.get(i).getKey()+":" +entries.get(i).getValue()); } } public static ArrayList<Map.Entry<String,Integer>> sortMap(Map map){ List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(map.entrySet()); Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> obj1 , Map.Entry<String, Integer> obj2) { return obj2.getValue() - obj1.getValue(); } }); return (ArrayList<Entry<String, Integer>>) entries; } }
此时是按照降序排序,如果想升序排序,则Comparator的 返回 改为obj1.getValue() - obj2.getValue();即可
总结:由于TreeMap主要是针对key进行默认排序的,但是有的时候我们需要对value进行排序,这时候主要采取的策略是 将map变为List,然后利用Collections.sort进行排序,同时重写Comparator方法,即可。
相关文章推荐
- Easyui 翻页不保存选中记录
- 优化UITableViewCell高度计算的那些事
- NGUI的UISprite动态染色的一种方法
- leetcode--Unique Binary Search Trees
- Android基础系列-----------GUI系统之WindowManagerService
- Android基础系列-----------GUI系统之Android的UI显示概述
- UIAlertView消息文本左对齐操作
- java.sql.SQLException: Incorrect string value
- easyui-ueditor
- [LeetCode] Implement Stack using Queues
- 51nod 1126 求递推序列的第N项 && hdu - 1005 Number Sequence (求周期)
- UI元素状态伪类选择器
- 3 way quick sort
- POJ 1458:Common Subsequence
- POJ 1458:Common Subsequence
- 非常不错的点餐系统应用源码完整版
- leetcode--Unique Binary Search Trees II
- A quick message queue benchmark: ActiveMQ, RabbitMQ, HornetQ, QPID, Apollo
- java 并发编程 AbstractQueuedSynchronizer 加锁和解锁分析
- UITableView的简单介绍和功能