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

Java如何筛选含指定子串的Map键并获取对应值最小的键

问题背景

现有键类型为String、值类型为Double的HashMap用于存储门店距离数据,初始化示例如下:

Map<String, Double> storeDistance = new HashMap<String, Double>();
storeDistance.put("10-ABCD-01", 15.75);
storeDistance.put("10-XYZ-05", 12.13);
storeDistance.put("10-ABCD-06", 11.06);
storeDistance.put("10-ABCD-04", 10.76);
storeDistance.put("10-XYZ-03", 7.62);

原示例初始化代码存在两处笔误:定义的Map变量名为storeDistance,后续put操作误用了变量名map;浮点数07.62前置的0无意义,Java中直接写7.62即可。

需求为:筛选所有键中包含指定子串(如示例中的"ABCD")的条目,找到其中距离值最小的条目对应的键,上述示例预期返回结果为"10-ABCD-04"。

原实现代码问题

你之前写的Stream流代码无法运行,核心问题有两个:

  • 流操作从keySet()出发,经过filter后直接调用map(storeDistance::get)将流元素转换为纯Double类型的距离值,后续流里已经没有key信息,根本无法调用Map.Entry::getKey、Map.Entry::getValue这类Entry相关方法
  • 选用Collectors.toMap作为收集器不符合需求,这个收集器的作用是将流元素组装为新的Map,本身不具备查找最小值的能力,你写的参数逻辑和收集器要求的参数格式也不匹配。
正确实现代码

推荐写法(逻辑简洁,性能更好)

直接遍历Map的entrySet,过滤后调用min方法找最小值即可:

String targetKey = storeDistance.entrySet().stream()
        .filter(entry -> entry.getKey().contains("ABCD"))
        .min(Comparator.comparingDouble(Map.Entry::getValue))
        .map(Map.Entry::getKey)
        // 无匹配条目时的默认返回值可根据业务需求调整,也可以抛异常
        .orElse(null);

运行后targetKey的取值就是预期的"10-ABCD-04"。

适配原思路的写法

如果你想沿用原来尝试的Math::min合并逻辑,可以用collectingAndThen组合收集器实现:

String targetKey = storeDistance.entrySet().stream()
        .filter(entry -> entry.getKey().contains("ABCD"))
        .collect(Collectors.collectingAndThen(
                Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        Math::min
                ),
                resultMap -> resultMap.entrySet().stream()
                        .min(Comparator.comparingDouble(Map.Entry::getValue))
                        .map(Map.Entry::getKey)
                        .orElse(null)
        ));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 19:12:28