Java 8 – How to sort a Map
Java 8 – How to sort a Map
1. Quick Explanation
Map result = map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
2. Sort by KEYS
package com.mkyong.test;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class SortByKeyExample {
public static void main(String[] argv) {
Map<String, Integer> unsortMap = new HashMap<>();
unsortMap.put("z", 10);
unsortMap.put("b", 5);
unsortMap.put("a", 6);
unsortMap.put("c", 20);
unsortMap.put("d", 1);
unsortMap.put("e", 7);
unsortMap.put("y", 8);
unsortMap.put("n", 99);
unsortMap.put("g", 50);
unsortMap.put("m", 2);
unsortMap.put("f", 9);
System.out.println("Original...");
System.out.println(unsortMap);
// sort by keys, a,b,c..., and return a new LinkedHashMap
// toMap() will returns HashMap by default, we need LinkedHashMap to keep the order.
Map<String, Integer> result = unsortMap.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
// Not Recommend, but it works.
//Alternative way to sort a Map by keys, and put it into the "result" map
Map<String, Integer> result2 = new LinkedHashMap<>();
unsortMap.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));
System.out.println("Sorted...");
System.out.println(result);
System.out.println(result2);
}
}
Output
Original
{a=6, b=5, c=20, d=1, e=7, f=9, g=50, y=8, z=10, m=2, n=99}
Sorted...
{a=6, b=5, c=20, d=1, e=7, f=9, g=50, m=2, n=99, y=8, z=10}
{a=6, b=5, c=20, d=1, e=7, f=9, g=50, m=2, n=99, y=8, z=10}
3. Sort by Values
package com.mkyong.test;
package com.mkyong;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class SortByValueExample {
public static void main(String[] argv) {
Map<String, Integer> unsortMap = new HashMap<>();
unsortMap.put("z", 10);
unsortMap.put("b", 5);
unsortMap.put("a", 6);
unsortMap.put("c", 20);
unsortMap.put("d", 1);
unsortMap.put("e", 7);
unsortMap.put("y", 8);
unsortMap.put("n", 99);
unsortMap.put("g", 50);
unsortMap.put("m", 2);
unsortMap.put("f", 9);
System.out.println("Original...");
System.out.println(unsortMap);
//sort by values, and reserve it, 10,9,8,7,6...
Map<String, Integer> result = unsortMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
//Alternative way
Map<String, Integer> result2 = new LinkedHashMap<>();
unsortMap.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));
System.out.println("Sorted...");
System.out.println(result);
System.out.println(result2);
}
}
Output
Original...
{a=6, b=5, c=20, d=1, e=7, f=9, g=50, y=8, z=10, m=2, n=99}
Sorted...
{n=99, g=50, c=20, z=10, f=9, y=8, e=7, a=6, b=5, m=2, d=1}
{n=99, g=50, c=20, z=10, f=9, y=8, e=7, a=6, b=5, m=2, d=1}
4. Map<Object,Object>
package com.mkyong;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;
public class DisplayApp {
public static void main(String[] args) {
Properties properties = System.getProperties();
// not easy to sort this
Set<Map.Entry<Object, Object>> entries = properties.entrySet();
LinkedHashMap<String, String> collect = entries.stream()
//Map<String, String>
.collect(Collectors.toMap(k -> (String) k.getKey(), e -> (String) e.getValue()))
.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
collect.forEach((k, v) -> System.out.println(k + ":" + v));
}
}
http://www.mkyong.com/java8/java-8-how-to-sort-a-map/
Java 8 – How to sort a Map的更多相关文章
- Java语言利用Collections.sort对Map,List排序
1.main方法包含TreeMap排序1,TreeMap排序2,HashMap排序,List<Integer>排序,List<Bean>排序,List<Map>排序 ...
- python 中的sort 和java中的Collections.sort()函数的使用
x=[1,2,3] x.sort()对的,x这个都变了 y=x.sort()错误 y=sorted(x)对的,x拍好序的一个副本 python中用匿名函数和自定义函数排序:(很奇怪的是比较函数返回的是 ...
- Java集合中List,Set以及Map等集合体系详解
转载请注明出处:Java集合中List,Set以及Map等集合体系详解(史上最全) 概述: List , Set, Map都是接口,前两个继承至collection接口,Map为独立接口 Set下有H ...
- Java 容器源码分析之 Map
ava.util 中的集合类包含 Java 中某些最常用的类.最常用的集合类是 List 和 Map.List 的具体实现包括 ArrayList 和 Vector,它们是可变大小的列表,比较适合构建 ...
- 【转】Java学习---Java核心数据结构(List,Map,Set)使用技巧与优化
[原文]https://www.toutiao.com/i6594587397101453827/ Java核心数据结构(List,Map,Set)使用技巧与优化 JDK提供了一组主要的数据结构实现, ...
- Java并发包——线程安全的Map相关类
Java并发包——线程安全的Map相关类 摘要:本文主要学习了Java并发包下线程安全的Map相关的类. 部分内容来自以下博客: https://blog.csdn.net/bill_xiang_/a ...
- 报错:java.lang.ClassNotFoundException: org.codehaus.jackson.map.JsonMappingException
报错背景: 执行hdfs-mysql的job任务的时候报错. 报错现象: Exception has occurred during processing command Exception: org ...
- Java开发中使用sort排序
Java开发中使用sort排序 BaiduSpring https://baijiahao.baidu.com/s?id=1625440912158830354&wfr=spider& ...
- java中将jsonObject字符串转化为Map对象
java中将jsonObject字符串转化为Map对象 1.我们这里使用json-lib包进行转换,可在http://json-lib.sourceforge.net/下载依赖于下面的jar包: ja ...
随机推荐
- IPC's epoch 6 is less than the last promised epoch 7
一.错误起因 Active NameNode日志出现异常IPC‘s epoch [X] is less than the last promised epoch [X+1],出现短期的双Active ...
- 微信小程序 - 步骤条组件
<!-- 未激活颜色: uncolor:'#ccc' 激活 active:0 数据源 data:[{},{}] 步骤条类型:type basic detail num more --> & ...
- webkit webApp 开发技术要点总结[转]
http://www.cnblogs.com/pifoo/archive/2011/05/28/webkit-webapp.html 如果你是一名前端er,又想在移动设备上开发出自己的应用,那怎么实现 ...
- Page Visibility实现焦点丢失提醒
0.前言 HTML5 Page Visibility API是一个很实用的特性.当页面对用户不可见时,暂停播放页面中的视频.动画.声音.以及其它耗费内存的操作,等用户回来时.再继续这些操作. 当然,最 ...
- 解决 ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)
在/etc/hosts文件中加入下面一行内容 127.0.0.1 localhost.localdomain localhost
- Plus One 加一运算
Given a non-negative number represented as an array of digits, plus one to the number. The digits ar ...
- Oracle Data Integrator 12c-----场景(Scenario)和调度(Schedule)
1 生成场景 Designer->项目->ODI_Exercise ->第一个文件夹->包->First _Pkg,右键,"生成场景" " ...
- 〖前端开发〗HTML/CSS基础知识学习笔记
经过一天的学习,把慕课网的HTML/CSS基础知识学完了,笔记整理: 1. 文件结构: HTML文件的固定结构: <html> <head>...</head> & ...
- docker 实战---多台物理主机的联网,容器桥接到物理网络拓扑图(四)
非常多朋友说上一篇中对网络的描写叙述不够清楚,感谢热心的群友彩笔程序猿: 提供了他理解的图,在这里贴一下: 我自己也补画了一副多台机器互联的图,欢迎大家留言讨论: 主机A和主机B的网卡一都连着物理交换 ...
- 如何导出标准模板库(STL)类的实例化和包含STL类对象数据成员的类
本文翻译自 https://support.microsoft.com/zh-cn/help/168958/how-to-export-an-instantiation-of-a-standard-t ...