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. C# FTP常规方法

    using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using Sy ...

  2. 去掉JAVA部分依赖的事例

    一.现象 最近做JAVA项目,需要依赖一个外部的JAR包,但是依赖之后,发现eclipse一直workspace,估计是包重复加载的问题 二.问题 使用查看包依赖的命令:mvn dependency: ...

  3. [转]基本Guava工具

    转自:http://www.cnblogs.com/renchunxiao/p/3661918.html?utm_source=tuicool 使用Joiner类 将任意字符串通过分隔符进行连接到一起 ...

  4. HDFS之FileStatus

    任何文件系统的一个重要特性都是提供其目录结构浏览和检索它所存文件和目录相关信息的功能.FileStatus对象封装了文件系统中文件和目录的元数据,包括文件的长度.块大小.备份数.修改时间.所有者以及权 ...

  5. 简单的tcp聊天

    package com.pers.tcptest; import java.io.IOException; import java.io.InputStream; import java.io.Out ...

  6. infobright系列二:数据迁移

    安装之后把之前infobright的数据迁移到新安装的infobright上. 1:挺掉相关的服务 2:scp 把旧数据拷到新安装的infobright上 3:修改/etc/my-ib.cnf的数据目 ...

  7. pyDes介绍

    使用参数如下(拷贝自上述提供的地址): Class initialization -------------------- pyDes.des(key, [mode], [IV], [pad], [p ...

  8. 用RotateDrawable实现网易云音乐唱片机效果

    imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="唱片机" title=""> ...

  9. 【DB2】建造测试数据

    建表语句 CREATE TABLE     FUND_DAILY_INCOME     (         ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTIT ...

  10. HTML5 Audio标签方法和函数API介绍

    问说网 > 文章教程 > 网页制作 > HTML5 Audio标签方法和函数API介绍 Audio APIHTML5HTML5 Audio预加载 HTML5 Audio标签方法和函数 ...