Search code examples
javajava-8guava

Creating an ImmutableList from an Iterable


I need to fetch an object from each element in an Iterable and add it into a List.

I am able to do this using the code below. However, are there any ways of creating a Guava ImmutableList without instantiating a List explicitly?

List<Data> myList = new ArrayList<>();
myIterable.forEach(val ->
  myList.add(val.getMetaData())
);

Solution

  • To apply a function to each element and turn it into an ImmutableList, today's best practice would be

    Streams.stream(myIterable).map(Value::getMetaData)
      .collect(ImmutableList.toImmutableList());