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

如何访问ArrayList<LinkedHashMap<K,V>>中的id值?

如何从LinkedHashMap中获取id的值?

LinkedHashMap 是基于键值对存储的 Map 实现,本身不支持 ArrayList 那样的索引访问逻辑,想要获取"id"对应的值,有两种常用方式:

方法一:直接使用Map的get()方法(推荐)

这是最直接高效的方式,利用键来直接取值:

// 假设你的LinkedHashMap实例名为map
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
map.put("id", 1);
map.put("name", "A");
map.put("status", "ACTIVE");

// 获取id的值,注意类型转换
Integer idValue = (Integer) map.get("id");

注意:

  • 键的大小写是敏感的,必须和存入时的"id"完全一致;
  • 如果担心键不存在导致返回null,可以先通过map.containsKey("id")做存在性判断,避免空指针异常。

方法二:通过键集合转ArrayList间接获取(不推荐)

如果非要模拟ArrayList的索引访问逻辑,可以先把LinkedHashMap的键集合转成ArrayList,再通过索引拿到键后取值:

// 将map的键集合转为ArrayList
ArrayList<String> keyList = new ArrayList<>(map.keySet());
// LinkedHashMap会保留插入顺序,所以"id"是第一个元素(索引0)
String idKey = keyList.get(0);
Integer idValue = (Integer) map.get(idKey);

这种方式依赖键的插入顺序,一旦后续插入顺序改变,索引对应的键就会出错,所以仅在特殊场景下使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:52:00