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

无需逐个调用Map::keySet,如何从Map列表中提取所有键?

Java 提取List<Map<String, Integer>>中所有键的简便方法

直接用Java 8及以上版本的Stream API就能搞定,不用手动写遍历循环,代码简洁高效:

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

// 提取所有键(包含重复键)
List<String> allKeys = myList.stream()
    .flatMap(map -> map.keySet().stream())
    .collect(Collectors.toList());

代码说明:

  • myList.stream():将列表转换为Stream流,开启流式操作
  • flatMap(map -> map.keySet().stream()):把每个Map的键集合(keySet)转成独立的Stream,再合并成一个全局的Stream,避免嵌套流的问题
  • collect(Collectors.toList()):将最终的Stream收集成List类型的结果

示例验证:

假设你的列表是:

List<Map<String, Integer>> myList = List.of(
    Map.of("Bob", 1),
    Map.of("James", 5)
);

运行上述代码后,allKeys的结果就是 ["Bob", "James"]。

额外需求:去重键

如果你的列表中存在重复的键,需要提取唯一键的话,在流式操作中加入distinct()即可:

List<String> uniqueKeys = myList.stream()
    .flatMap(map -> map.keySet().stream())
    .distinct()
    .collect(Collectors.toList());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 22:54:57