91名师指路-头部
91名师指路

lambda 对Map根据key或value进行排序

由于某些原因,现在不支持支付宝支付,如需要购买源码请加博主微信进行购买,微信号:13248254750

一:根据Map中的key进行排序

/**
* 功能:根据map中的key进行排序
* 网址:https://91mszl.com
* @Author: zxb
* @Date: 2022-04-11 11:21:41
*/
public static void main(String[] args) {
Map<String, String> map=new HashMap<String, String>();
map.put("2022年05月", "吃饭");
map.put("2022年04月", "睡觉");
map.put("2022年06月", "去超市");

Map<String, String> sortedMap = map.entrySet().stream().sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray()));
}

执行结果:

Sorted Map: [2022年04月=睡觉, 2022年05月=吃饭, 2022年06月=去超市]


二:根据Map中的value进行排序

/**
* 功能:根据map中的value进行排序
* 网址:https://91mszl.com
* @Author: zxb
* @Date: 2022-04-11 11:21:41
*/
public static void main(String[] args) {
Map<String, String> map=new HashMap<String, String>();
map.put("2022年05月", "33");
map.put("2022年04月", "22");
map.put("2022年06月", "55");
Map<String, String> sortedMap = map.entrySet().stream().sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray()));
}

执行结果:

Sorted Map: [2022年04月=22, 2022年05月=33, 2022年06月=55]




2022-04-11 11:28:00     阅读(396)

名师出品,必属精品    https://www.91mszl.com

联系博主    
用户登录遮罩层
x

账号登录

91名师指路-底部