You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何用Stream优化两个HashMap列表的对比逻辑并返回布尔值

Java HashMap列表对比纯Stream优化实现

优化点说明

  • 提前将productDetailsFromApplication转换为以ProductName为键的查找Map,避免原实现中每次校验都遍历两次application列表的性能损耗
  • 全流程采用Stream API实现,无显式for循环
  • 移除Assert断言,校验失败直接返回布尔值,保留原有日志打印逻辑
  • 采用allMatch短路特性,任意校验项失败立即终止后续校验,和原实现提前返回的逻辑一致

实现代码

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

// 校验方法实现
public boolean validateProductLists(List<HashMap<String, Object>> productDetailsFromInputData, 
                                    List<HashMap<String, Object>> productDetailsFromApplication) {
    // 预处理应用侧列表,转为ProductName到对应属性Map的查找表,重复key默认保留第一个,可按需调整合并逻辑
    Map<String, HashMap<String, Object>> appProductMap = productDetailsFromApplication.stream()
            .collect(Collectors.toMap(
                    product -> product.get("ProductName").toString(),
                    product -> product,
                    (oldVal, newVal) -> oldVal
            ));

    // 全Stream校验输入侧所有产品
    return productDetailsFromInputData.stream().allMatch(inputProduct -> {
        String productName = inputProduct.get("ProductName").toString();
        String inputQuantity = inputProduct.get("Quantity").toString();
        String inputPerpetual = inputProduct.get("Perpetual").toString();
        LOGGER.info("Validating Product details for Product {}", productName);

        // 校验产品是否存在于应用侧
        if (!appProductMap.containsKey(productName)) {
            LOGGER.error("Did not find any matching Product Name with the given details in App, ProductName: {}", productName);
            return false;
        }

        HashMap<String, Object> appProduct = appProductMap.get(productName);
        LOGGER.info("Found the Product details in SFDC matching with input data, ProductName: {}", productName);
        String appQuantity = appProduct.get("Quantity").toString();
        String appPerpetual = appProduct.get("Perpetual").toString();

        // 校验数量
        if (!inputQuantity.equalsIgnoreCase(appQuantity)) {
            LOGGER.error("APP Quantity does not matches with Input Quantity for Product {} | App Quantity {} | Input Quantity {}",
                    productName, appQuantity, inputQuantity);
            return false;
        }

        // 校验永久授权标识
        if (!inputPerpetual.equalsIgnoreCase(appPerpetual)) {
            LOGGER.error("App Perpetual value does not matches with Input Perpetual value for Product {} | App Perpetual {} | Input perpetual {}",
                    productName, appPerpetual, inputPerpetual);
            return false;
        }

        // 所有校验通过
        return true;
    });
}

内容的提问来源于stack exchange,提问作者Kovid Mehta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 05:06:04