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 ...
随机推荐
- 使用树莓派3获取CPU温度
一.命令: cat /sys/class/thermal/thermal_zone0/temp 二.上图:
- 如何处理Android中的防缓冲区溢出技术
[51CTO专稿]本文将具体介绍Android中的防缓冲区溢出技术的来龙去脉. 1.什么是ASLR? ASLR(Address space layout randomization)是一种针对缓冲区溢 ...
- 不同版本的tomcat下载路径
1.由于安全问题,有些tomcat存在漏洞.为了升级要么修复漏洞,要么就直接升级tomcat. 一般升级tomcat比较省事.但是找到相应版本的tomcat比较难,所以还是要自己寻找对应的tomcat ...
- MongoDB副本集配置系列五:副本集的在线迁移
MongoDB副本集的在线迁移 查看当前集群的状态: { "setName" : "gechongrepl", "setVersion" : ...
- Python学习摘录(上)
1:接收输入 var=raw_input() 注意:raw_input()总数接收字符串形式的输入.所以,如果我们想接收其他类型的数据,则需要强制类型转换.(如果转换失败,就会抛出异常) 2:pass ...
- psql 查询表大小
select schemaname,tablename,pg_relation_size(schemaname||'.'||tablename) as tabsize from pg_tables o ...
- ACE .i .inl文件(转)
在ACE的源代码目录里,有源文件.cpp.头文件.h,我们还发现有以.i和.inl为扩展名的文件.其实,以.i和.inl为扩展名的文件是ACE源码中inline函数的存放形式. 在说明ACE中为什么采 ...
- 用OpenSSL把二进制的Cer证书转换程Base64格式的PEM格式的证书
openssl x509 -inform der -in /d/ty.cer -pubkey -noout > /d/certificate_publickey.pem
- django之创建第7-2个项目-url配置分离
1.urls.PY分离 # -*- coding: UTF-8 -*- from django.conf.urls import patterns, include, url # Uncomment ...
- redmine3.3基于bitnami集成快速安装
形而上学,此景此情,古今一般同!好的东西,逢人喜!redmine在当下还是不错的. 源码安装redmine,相对复杂基于ruby运行的!化繁为简实!追究极致万物! 00.环境及软件说明 bitnami ...