Map排序的方式有很多种,这里记录下自己总结的两种比较常用的方式:按键排序(sort by key), 按值排序(sort by value)。

1、按键排序

jdk内置的java.util包下的TreeMap<K,V>既可满足此类需求,向其构造方法 TreeMap(Comparator<? super K> comparator)  传入我们自定义的比较器即可实现按键排序。

实现代码

public class MapSortDemo {

    public static void main(String[] args) {

        Map<String, String> map = new TreeMap<String, String>();

        map.put("KFC", "kfc");
map.put("WNBA", "wnba");
map.put("NBA", "nba");
map.put("CBA", "cba"); Map<String, String> resultMap = sortMapByKey(map); //按Key进行排序 for (Map.Entry<String, String> entry : resultMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
} /**
* 使用 Map按key进行排序
* @param map
* @return
*/
public static Map<String, String> sortMapByKey(Map<String, String> map) {
if (map == null || map.isEmpty()) {
return null;
} Map<String, String> sortMap = new TreeMap<String, String>(
new MapKeyComparator()); sortMap.putAll(map); return sortMap;
}
} 比较器类 class MapKeyComparator implements Comparator<String>{ @Override
public int compare(String str1, String str2) { return str1.compareTo(str2);
}
}

2、按值排序

按值排序就相对麻烦些了,貌似没有直接可用的数据结构能处理类似需求,需要我们自己转换一下。
Map本身按值排序是很有意义的,很多场合下都会遇到类似需求,可以认为其值是定义的某种规则或者权重。

原理:将待排序Map中的所有元素置于一个列表中,接着使用Collections的一个静态方法 sort(List<T> list, Comparator<? super T> c) 
来排序列表,同样是用比较器定义比较规则。排序后的列表中的元素再依次装入Map,为了肯定的保证Map中元素与排序后的List中的元素的顺序一致,使用了LinkedHashMap数据类型。

实现代码

public class MapSortDemo {

    public static void main(String[] args) {

        Map<String, String> map = new TreeMap<String, String>();

        map.put("KFC", "kfc");
map.put("WNBA", "wnba");
map.put("NBA", "nba");
map.put("CBA", "cba"); Map<String, String> resultMap = sortMapByKey(map); //按Key进行排序
// Map<String, String> resultMap = sortMapByValue(map); //按Value进行排序 for (Map.Entry<String, String> entry : resultMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
} /**
* 使用 Map按value进行排序
* @param map
* @return
*/
public static Map<String, String> sortMapByValue(Map<String, String> oriMap) {
if (oriMap == null || oriMap.isEmpty()) {
return null;
}
Map<String, String> sortedMap = new LinkedHashMap<String, String>();
List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(
oriMap.entrySet());
Collections.sort(entryList, new MapValueComparator()); Iterator<Map.Entry<String, String>> iter = entryList.iterator();
Map.Entry<String, String> tmpEntry = null;
while (iter.hasNext()) {
tmpEntry = iter.next();
sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
}
return sortedMap;
}
}

比较器类

class MapValueComparator implements Comparator<Map.Entry<String, String>> {

    @Override
public int compare(Entry<String, String> me1, Entry<String, String> me2) { return me1.getValue().compareTo(me2.getValue());
}
}

Java Map 按Key排序和按Value排序的更多相关文章

  1. Java Map获取key和value 以及String字符串转List方法

    一.问题描述 这里描述两个问题: 1.Java Map获取key和value的方法: 2.String字符串转List的方法: 二.解决方法 1.Java Map获取key和value的方法   2. ...

  2. Java Map按键(Key)排序和按值(Value)排序

    Map排序的方式有很多种,两种比较常用的方式:按键排序(sort by key), 按值排序(sort by value).1.按键排序jdk内置的java.util包下的TreeMap<K,V ...

  3. Java Map 按Key排序和按Value排序【转】【补】

    package kingtool.sort; import java.util.ArrayList; import java.util.Collections; import java.util.Co ...

  4. Java map 详解 - 用法、遍历、排序、常用API等

    尊重原创: http://www.cnblogs.com/lzq198754/p/5780165.html 概要: java.util 中的集合类包含 Java 中某些最常用的类.最常用的集合类是 L ...

  5. java Map 迭代key,value 最简洁的方法

    import java.util.HashMap; import java.util.Map; public class EntrySets { public static void main(Str ...

  6. java Map按Key排序

    public static void main(String[] args) { Map<String, String> map = new TreeMap<String, Stri ...

  7. java map 当key相同的时候 最后一个覆盖最近的一个值

  8. map的key排序

    java map的key排序吗 java为数据结构中的映射定义了一个接口java.util.Map,他实现了四个类,分别是:HashMap,HashTable,LinkedHashMapTreeMap ...

  9. Java Map集合按照key和value排序之法

    一.理论基点 Map是键值对的集合接口,它的实现类主要包括:HashMap,TreeMap,Hashtable以及LinkedHashMap等. TreeMap:基于红黑树(Red-Black-Tre ...

随机推荐

  1. FlyCapture2 Qt5 MinGW Configuration

    Install FlyCatprue2 to the folder "C:\PointGreyResearch\" Add the following to the .pro fi ...

  2. empty与isset的一点使用体会

    刚在做表单提交的时候,我想检验一下数据是否存在,并用var_dump函数看一下数据.首先看使用isset()的代码 //登录函数 function login(){ if(!isset($_POST) ...

  3. Java表单类双击提交

    双击制御 有些时候一些操作会非常的耗费时间(Long Lived Operation),例如这个数据库的导出,表表生成等.有些时候程序的使用者看到很长时间服务器 没有反应,倾向于多次点击提交按钮.这样 ...

  4. JBoss错误

    jboss进程在启动时碰到Address already in use: JVM_Bind /0.0.0.0:8080错误. 这个错误的含义是8080端口被占用了. 解决方法: 方法1: 开始--运行 ...

  5. Excel中如何在两个工作表中查找重复数据

    有时我们可能会在两种工作表中查找重复记录,当数据记录很多时,就必须通过简单的方法来实现.下面小编就与大家一起分享一下查看重复记录数据的方法,希望对大家有所帮助. 方法/步骤   为了讲解的需要,小编特 ...

  6. VC++6.0 显示行号

    通过VC6LineNumberAddin能够解决这个问题,方法如下. 一.下载该文件. 网上很多免费的. 二.使用方法:            [1]:打开VC++6.0,点击菜单“工具(Tools) ...

  7. Javascript 笔记与总结(2-5)window 对象

    浏览器 window 对象(BOM)是浏览器宿主对象,和 js 语言无关. [window 对象的方法] window.alert(message); window.confirm(message); ...

  8. Web 在线文件管理器学习笔记与总结(17)复制文件 (18)剪切文件

    (17)复制文件 ① 复制文件通过copy($src,$dst) 来实现 ② 检测目标目录是否存在,如果存在则继续检测目标目录中是否存在同名文件,如果不存在则复制成功 file.func.php 中添 ...

  9. cURL 学习笔记与总结(1)概念

    概念: cURL(Client URL Library Functions)is a command line tool for transfering data with URL syntax(使用 ...

  10. what is php?

    PHP is a popular general-purpose scripting language that is especially suited to web development. Fa ...