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

如何从Iterable直接创建Guava ImmutableList?

解决方案

当然可以不用显式实例化List来创建Guava的ImmutableList,用Guava自带的工具类就能一步完成转换:

方法一:Iterables.transform() + ImmutableList.copyOf()

这是最简洁的方式,Iterables.transform()会生成一个懒加载的转换后Iterable,再通过ImmutableList.copyOf()直接构建不可变列表,全程无需手动创建中间集合:

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;

// 直接生成ImmutableList,无需中间ArrayList
ImmutableList<Data> myImmutableList = ImmutableList.copyOf(
    Iterables.transform(myIterable, val -> val.getMetaData())
);

方法二:ImmutableList.Builder

如果需要更灵活的构建(比如额外添加元素),也可以用ImmutableList.Builder配合转换后的Iterable:

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;

ImmutableList<Data> myImmutableList = ImmutableList.<Data>builder()
    .addAll(Iterables.transform(myIterable, val -> val.getMetaData()))
    // 这里可以额外添加其他元素
    // .add(additionalData)
    .build();

说明

  • Iterables.transform()是懒执行的,不会提前把所有元素都转换好,直到ImmutableList.copyOf()或Builder.addAll()遍历它时才会执行转换,避免了不必要的内存开销。
  • 最终得到的ImmutableList是不可变的,符合Guava不可变集合的特性,线程安全且性能更优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 08:15:36