如何从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
相关产品推荐
相关产品推荐

