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

如何从MultiMap中获取指定索引的键关联值?

实现ArrayListMultimap按索引获取指定值

因为你用的ArrayListMultimap,每个key对应的取值集合本身就是有序的ArrayList,所以可以通过以下方式实现类似get(key, index)的功能:

直接实现方式

先获取对应key的取值列表,再通过索引访问:

// 替换成你的目标key
String targetKey = "yourKey";
// 获取该key对应的所有值(ArrayListMultimap返回的是ArrayList视图)
List<Player> playerList = (List<Player>) players.get(targetKey);
// 获取第12个值(注意:Java集合索引从0开始,第12个对应索引11)
if (playerList.size() > 11) {
    Player targetPlayer = playerList.get(11);
    // 处理你的逻辑
} else {
    // 处理索引越界的情况
}

封装成通用工具方法

如果需要多次使用,可以封装成工具方法,同时兼容其他Multimap实现:

public static <K, V> V getMultimapValue(Multimap<K, V> multimap, K key, int index) {
    Collection<V> values = multimap.get(key);
    
    // 先校验索引合法性
    if (index < 0 || index >= values.size()) {
        throw new IndexOutOfBoundsException("索引: " + index + ", 当前值集合大小: " + values.size());
    }
    
    // 针对ArrayListMultimap做优化,直接强转成List访问
    if (values instanceof List) {
        return ((List<V>) values).get(index);
    }
    
    // 其他Multimap实现用迭代器遍历到指定索引
    Iterator<V> iterator = values.iterator();
    for (int i = 0; i < index; i++) {
        iterator.next();
    }
    return iterator.next();
}

调用示例:

// 获取第12个元素(索引11)
Player player = getMultimapValue(players, "yourKey", 11);

注意事项

  • ArrayListMultimap的get(key)返回的是原集合的视图,强转成List是安全的,不会产生额外的复制开销
  • 务必注意集合索引从0开始,不要混淆"第N个元素"和索引值
  • 封装的工具方法同时支持其他Multimap实现(比如LinkedListMultimap),兼容性更强

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:20:07