Java8中Map函数应用
-
computeIfAbsent函数
computeIfAbsent方法的逻辑是,如果map中没有(Absent)相应的key,则执行lambda表达式生成一个默认值并放入map中并返回,否则返回map中已有的值。
List<Payment> payments = getPayments();
Map<Integer, List<Payment>> paymentByTypeMap = new HashMap<>();
for(Payment payment : payments){
paymentByTypeMap.computeIfAbsent(payment.getPayTypeId(), k -> new ArrayList<>())
.add(payment);
}
-
computeIfPresent函数
computeIfPresent函数与computeIfAbcent的逻辑是相反的,如果map中存在(Present)相应的key,则对其value执行lambda表达式生成一个新值并放入map中并返回,否则返回null。
List<Payment> payments = getPayments();
//将payment关联到相关的order上
for(Payment payment : payments){
orderPaymentMap.computeIfPresent(payment.getOrderId(),
(k, orderPayment) -> orderPayment.addPayment(payment));
}
-
compute函数
compute() 方法对 hashMap 中指定 key 的值进行重新计算。
import java.util.HashMap;
class Main {
public static void main(String[] args) {
//创建一个 HashMap
HashMap<String, Integer> prices = new HashMap<>();
// 往HashMap中添加映射项
prices.put("Shoes", 200);
prices.put("Bag", 300);
prices.put("Pant", 150);
System.out.println("HashMap: " + prices);
// 重新计算鞋子打了10%折扣后的值
int newPrice = prices.compute("Shoes", (key, value) -> value - value * 10/100);
System.out.println("Discounted Price of Shoes: " + newPrice);
// 输出更新后的HashMap
System.out.println("Updated HashMap: " + prices);
}
-
merge函数
merge的第一个参数是key,第二个参数是value,第三个参数是值合并函数。
如果 key 对应的 value 不存在,则返回该 value 值,如果存在,则返回通过 remappingFunction 重新计算后的值。
List<Payment> payments = getPayments();
Map<Integer, BigDecimal> amountByTypeMap = new HashMap<>();
for(Payment payment : payments){
amountByTypeMap.merge(payment.getPayTypeId(), payment.getAmount(), BigDecimal::add);
}
-
forEach函数
# 经典循环法:
for(Map.Entry<String, BigDecimal> entry: amountByTypeMap.entrySet()){
Integer payTypeId = entry.getKey();
BigDecimal amount = entry.getValue();
System.out.printf("payTypeId: %s, amount: %s \n", payTypeId, amount);
}
# 用forEach
amountByTypeMap.forEach((payTypeId, amount) -> {
System.out.printf("payTypeId: %s, amount: %s \n", payTypeId, amount);
});
分类:
Java类
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?