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

如何用Stream实现基于List值匹配过滤Map<String, List<String>>的键?

解决方案

实现代码

String s = "Downloaded";
Map<String, List<String>> m = Map.ofEntries(
        Map.entry("Download", List.of("Download", "Downloading,", "Downloaded")),
        Map.entry("Upload", List.of("Upload", "Uploading,", "Uploaded"))
);

// 获取第一个匹配的键(若需所有匹配结果,改用collect(Collectors.toList()))
Optional<String> matchedKey = m.entrySet().stream()
        .filter(entry -> entry.getValue().stream()
                .anyMatch(item -> s.contains(item) || item.contains(s)))
        .map(Map.Entry::getKey)
        .findFirst();

// 输出结果
matchedKey.ifPresent(key -> System.out.println("匹配的键:" + key));

逻辑说明

  1. 遍历Map条目:通过entrySet().stream()遍历Map的键值对,同时获取键和对应的值列表。
  2. 过滤匹配条件:
    • 对每个值列表,用anyMatch()检查是否存在符合要求的元素:
      • s.contains(item):判断s是否包含当前列表项(即列表项是s的子串)
      • item.contains(s):判断列表项是否包含s(即列表项是s的超字符串)
    • 只要满足两个条件中的任意一个,该键值对就会被保留。
  3. 提取结果:
    • map(Map.Entry::getKey)将符合条件的键值对转换为对应的键。
    • findFirst()返回第一个匹配的键(用Optional处理无匹配的情况);如果需要所有匹配的键,替换为collect(Collectors.toList())即可。

示例输出

对于给定的s = "Downloaded",代码会输出:匹配的键:Download

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 10:03:12