stream流对map的key和value进行排序(支持字符串)

2021/4/19 18:58:30

本文主要是介绍stream流对map的key和value进行排序(支持字符串),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.方法介绍

Map.Entry.comparingByValue():根据value
Map.Entry.comparingByKey():根据key

2.具体代码

package com.zyp.test;


import com.google.common.collect.Maps;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author syl
 * @description map的stream流使用
 * @since 2021/4/19
 */
public class StreamMap {
    public static void main(String[] args) {
        Map<String,Integer> map= Maps.newHashMap();
        map.put("d",4);
        map.put("e",5);
        map.put("f",1);
        map.put("b",2);
        map.put("c",3);
        //根据key排序
        map.entrySet().stream().sorted(Map.Entry.comparingByKey(String::compareTo)).
                collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue,newValue)->oldValue, LinkedHashMap::new)).
                forEach((K,V)-> System.out.println(K+":"+V));
        //根据value排序
        System.out.println("------------------------------------");
        map.entrySet().stream().sorted(Map.Entry.comparingByValue(Integer::compareTo)).
                collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue,newValue)->oldValue, LinkedHashMap::new)).
                forEach((K,V)-> System.out.println(K+":"+V));
    }
}


这篇关于stream流对map的key和value进行排序(支持字符串)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程