Home > database >  Creating an ImmutableList from an Interable object
Creating an ImmutableList from an Interable object

Time:08-05

I need to fetch an object from each element in an iterable and add it to a List. I am able to do this using the code below. However are there any ways of creating a Guava ImmutableList with instantiating the List explicitly?

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

CodePudding user response:

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());

CodePudding user response:

are there any ways of creating an ImmutableList with instantiating the List explicitly?

Solution using standard JDK features

You can use StreamSupport.stream() to generate a stream out of your Iterable and then apply map() to transform to extract Data objects from stream elements and toList() to obtain an immutable list as the result:

List<Data> result = StreamSupport.stream(
        myIterable.spliterator(), // spliterator
        false                     // denotes whether the stream should be parallel or not
    )
    .map(MyClass::getMetaData)
    .toList();   // for Java 8 .collect(Collectors.toUnmodifiableList())

A simple Demo

JDK Stream API & Guava ImmutableList

The code might look like that:

List<Data> result = StreamSupport.stream(
        myIterable.spliterator(),
        false
    )                                               // Stream<MyClass>
    .map(MyClass::getMetaData)                      // Stream<Data>
    .collect(
        ImmutableList::<Data>builder,               // accumulation type - ImmutableList.Builder
        ImmutableList.Builder::add,                 // adding stream element into a builder
        (left, right) -> left.addAll(right.build()) // merging builders while executing in parallel
    )
    .build();   // building an ImmutableList
  • Related