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

Java方法改写为Lambda返回布尔值及嵌套Map存储优化问题

问题解答

1. 原有方法Lambda改写实现

你不需要在Lambda中显式编写return true逻辑,Java Stream提供的anyMatch()是短路操作,只要匹配到第一个符合条件的元素就会立即终止遍历并返回true,和你原有for循环的执行逻辑完全一致,同时增加了空指针防护,改写后代码如下:

private Map<String, Map<String, Integer>> availability;

public boolean hasAvailability(int quantity, String currentLocation, Product product) {
    return Optional.ofNullable(availability.get(product.getProductId()))
            .map(innerMap -> innerMap.entrySet().stream()
                    .anyMatch(entry -> entry.getKey().equalsIgnoreCase(currentLocation)
                            && entry.getValue() > quantity))
            // 对应productId不存在时直接返回false,避免空指针
            .orElse(false);
}

2. 更适配的内存存储方案

你的数据属于总量小、内层条目少的静态数据,嵌套Map不是最优选择,可根据后续扩展需求选以下方案:

  • 单层复合键Map:把productId和转成小写的location拼接为字符串作为唯一键,直接用Map<String, Integer>存储,不需要遍历内层Map,查询效率更高,小数据量下字符串拼接开销可以忽略,示例代码如下:
    private Map<String, Integer> availability;
    
    public boolean hasAvailability(int quantity, String currentLocation, Product product) {
        String key = String.format("%s|%s", product.getProductId(), currentLocation.toLowerCase());
        return Optional.ofNullable(availability.get(key))
                .map(count -> count > quantity)
                .orElse(false);
    }
    
  • 结构化键Map:如果后续可能扩展查询维度,可以定义Record类作为键,语义更清晰避免硬编码:
    // JDK16及以上支持Record,低版本可以自定义普通类重写equals和hashCode方法
    record InventoryKey(String productId, String location) {}
    
    private Map<InventoryKey, Integer> availability;
    
    public boolean hasAvailability(int quantity, String currentLocation, Product product) {
        InventoryKey key = new InventoryKey(product.getProductId(), currentLocation.toLowerCase());
        return Optional.ofNullable(availability.get(key))
                .map(count -> count > quantity)
                .orElse(false);
    }
    
  • 枚举类存储:如果CSV数据完全不会变更,也可以把所有库存条目定义为枚举常量,查询时直接遍历枚举即可,代码可维护性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 16:06:05