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排序
 		//(oldValue,newValue)->(newValue)指定value重复之后按照那个值输出       
 		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));
    }
}

你可能感兴趣的:(java基础,stream,字符串,lambda)