对map的值进行排序
2015-06-27 12:07
423 查看
package com.asp; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; public class MapUtil { /** * 按map的value升序排序 * * @param map * @param top * * @return */ public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueAsc( Map<K, V> map, int top) { List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>( map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<K, V>>() { public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); Map<K, V> result = new LinkedHashMap<K, V>(); for (Map.Entry<K, V> entry : list) { if (top-- == 0) { break; } result.put(entry.getKey(), entry.getValue()); } return result; } /** * 按map value降序排序 * * @param map * @param top * * @return */ public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueDesc( Map<K, V> map, int top) { List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>( map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<K, V>>() { public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) { return (o2.getValue()).compareTo(o1.getValue()); } }); Map<K, V> result = new LinkedHashMap<K, V>(); for (Map.Entry<K, V> entry : list) { if (top-- == 0) { break; } result.put(entry.getKey(), entry.getValue()); } return result; } /** * 按key排序 * * @param unsort_map * @return */ public static SortedMap<String, Object> mapSortByKey( Map<String, Object> unsort_map) { TreeMap<String, Object> result = new TreeMap<String, Object>(); Object[] unsort_key = unsort_map.keySet().toArray(); Arrays.sort(unsort_key); for (int i = 0; i < unsort_key.length; i++) { result.put(unsort_key[i].toString(), unsort_map.get(unsort_key[i])); } return result.tailMap(result.firstKey()); } }
相关文章推荐
- PowerShell脚本反引号用法实例:随时随地给代码换行
- perl system,exec,readpipe 函数
- 用74HC165读8个按键状态(转)
- 2015062703 - 郭子仪
- zergRush (CVE-2011-3874) 提权漏洞分析
- CodeForces 550E Brackets in Implications(构造)
- Java深入浅出系列(四)——深入剖析动态代理--从静态代理到动态代理的演化
- C++POST提交数据
- 链表
- strcat strcpy 使用出现的问题汇总
- Android中dip、dp、sp、pt和px的区别详解
- UIView的xib和UIViewController的xib的区别
- #面试题--求数组中满足条件(a[0..i-1]<=a[i]<=a[i+1..N-1])的元素
- pandas教程:[5]读取csv数据
- 黑马程序员——Java基础--接口
- mac 配置Python集成开发环境(Eclipse +Python+Pydev)
- 内存管理
- 线性表链式存储-使用c语言实现
- javascipt模拟生成form表单2种提交方式
- Windows下Nginx+Mysql+Php(wnmp)环境搭建