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的更多相关文章

  1. Java语言利用Collections.sort对Map,List排序

    1.main方法包含TreeMap排序1,TreeMap排序2,HashMap排序,List<Integer>排序,List<Bean>排序,List<Map>排序 ...

  2. python 中的sort 和java中的Collections.sort()函数的使用

    x=[1,2,3] x.sort()对的,x这个都变了 y=x.sort()错误 y=sorted(x)对的,x拍好序的一个副本 python中用匿名函数和自定义函数排序:(很奇怪的是比较函数返回的是 ...

  3. Java集合中List,Set以及Map等集合体系详解

    转载请注明出处:Java集合中List,Set以及Map等集合体系详解(史上最全) 概述: List , Set, Map都是接口,前两个继承至collection接口,Map为独立接口 Set下有H ...

  4. Java 容器源码分析之 Map

    ava.util 中的集合类包含 Java 中某些最常用的类.最常用的集合类是 List 和 Map.List 的具体实现包括 ArrayList 和 Vector,它们是可变大小的列表,比较适合构建 ...

  5. 【转】Java学习---Java核心数据结构(List,Map,Set)使用技巧与优化

    [原文]https://www.toutiao.com/i6594587397101453827/ Java核心数据结构(List,Map,Set)使用技巧与优化 JDK提供了一组主要的数据结构实现, ...

  6. Java并发包——线程安全的Map相关类

    Java并发包——线程安全的Map相关类 摘要:本文主要学习了Java并发包下线程安全的Map相关的类. 部分内容来自以下博客: https://blog.csdn.net/bill_xiang_/a ...

  7. 报错:java.lang.ClassNotFoundException: org.codehaus.jackson.map.JsonMappingException

    报错背景: 执行hdfs-mysql的job任务的时候报错. 报错现象: Exception has occurred during processing command Exception: org ...

  8. Java开发中使用sort排序

    Java开发中使用sort排序 BaiduSpring https://baijiahao.baidu.com/s?id=1625440912158830354&wfr=spider& ...

  9. java中将jsonObject字符串转化为Map对象

    java中将jsonObject字符串转化为Map对象 1.我们这里使用json-lib包进行转换,可在http://json-lib.sourceforge.net/下载依赖于下面的jar包: ja ...

随机推荐

  1. Linux Shell角本中的条件判断

    1.条件判断: if 使用: if condition; then commands; fi if else 使用: if condition; then commands; else if cond ...

  2. python2.7 安装pypcap出错 pcap.h not found

    python安装pypcap的时候出错 通过不断百度+google找到解决方案 https://segmentfault.com/q/1010000007273835/a-10200000072756 ...

  3. 解决 ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)

    在/etc/hosts文件中加入下面一行内容 127.0.0.1 localhost.localdomain localhost

  4. BI Admin Tools和目录管理器的连接配置

    BI管理(Admin Tools): BI Server 的管理工具,用来创建维护模型,并且能够管理安全,会话,变量等等.是用的最多的一个管理工具:这个工具可以编辑 rpd 文件也可以在线通过 ODB ...

  5. python之模块cmath

    # -*- coding: utf-8 -*-#python 27#xiaodeng#python之模块cmath #复数的数学函数,如log.tan.sin等函数用法,针对我目前的情况用途较少,暂不 ...

  6. Linux手工添加swap

    swap是一把双刃剑,在实践中发现,严重的会导致linux负载超高,失去响应kswap内存的信息转存到swap(硬盘)!,在内存较大的情况下不建议建立swap!!! 师夷长技以制夷! 1.root权限 ...

  7. onActivityResult 传递数据

    onActivityResult 传递数据 http://www.cnblogs.com/sipher/articles/2435078.html 如下图所示.当菜单项变多时,出现了垂直的滚动条,选项 ...

  8. javascript基础 思维导图2

    来源于:http://www.cnblogs.com/xianyulaodi/p/5886128.html 1.javascript数据类型 2.javascript数组 3.javascript运算 ...

  9. [翻译]01-ASP.NET MVC 3介绍

    前言 -------------------------- 最近,公司新架构使用asp.net mvc5,一直都是看书学习ASP.NET MVC的,书本毕竟是别人翻译过来的,所以里面可能某些地方翻译有 ...

  10. Linux桌面“彩”起来:桌面环境及窗口管理器大盘点

    2011-02-22 11:49:50   看到这个标题,很多人一定认为桌面环境和窗口管理器是一回事,但严格来说窗口管理器和桌面环境是有区别的.桌面环境(Desktop Environments)是最 ...