HashMap排序--Java8

package com.nyis.zf.test;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class MapSortTest {
	
	public static void main(String[] args) {  
		 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("j", 50);
	        unsortMap.put("m", 2);
	        unsortMap.put("f", 9);

	        System.out.println("Original...");
	        System.out.println(unsortMap);

	        Map<String, Integer> result = sortMapByValue(unsortMap);

	        System.out.println("Sorted...");
	        System.out.println(result);
    }
	
	public static Map<String, Integer> sortMapBykey(Map<String, Integer> unsortMap){
		Map<String, Integer> result = new LinkedHashMap<>();
		//sort by key, a,b,c..., and put it into the "result" map
        unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEachOrdered(x -> result.put(x.getKey(), x.getValue()));
        return result;
	}
	
	public static Map<String, Integer> sortMapByValue(Map<String, Integer> unsortMap){
		Map<String, Integer> result = new LinkedHashMap<>();
		//sort by value, and reserve, 10,9,8,7,6...
        unsortMap.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())  // reversed倒序,不指定类型,会默认为<java.util.Map.Entry<java.lang.Object,V>>
                .forEachOrdered(x -> result.put(x.getKey(), x.getValue()));
        return result;
	}

}

复制代码

参考链接

https://www.cnblogs.com/yucfeng/p/8794608.html

转载于:https://juejin.im/post/5ae1552ef265da0b9671eb3c

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值