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进行排序(支持字符串)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-29DataGrip使用ssh连接数据库的操作流程
- 2024-05-28SpringBoot3.2更新声明!
- 2024-05-28中外程序员到底有啥区别?
- 2024-05-25外企也半夜发布上线吗?
- 2024-05-24鸿蒙原生应用再新丁!芒果TV 入局鸿蒙
- 2024-05-22基本概念
- 2024-05-22检索数据
- 2024-05-22排序数据
- 2024-05-22基础过滤数据
- 2024-05-22通过逻辑操作符过滤数据