Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an ImmutableList from an Iterable

Tags:

java

java-8

guava

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())
);
like image 404
Punter Vicky Avatar asked May 14 '26 17:05

Punter Vicky


2 Answers

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());
like image 171
Louis Wasserman Avatar answered May 16 '26 06:05

Louis Wasserman


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<Data>
        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

To future readers:
The last code snippet which makes use of ImmutableList.Builder provided for rather educational purposes. If you are not particularly interested in ImmutableList from Guava library (for instance, you're not using this library in your project) then have a look at the solution at the very beginning of the answer. If you do want Guava's ImmutableList for some reason, then the better option would be to use the approach provided in the answer by Louis Wasserman
like image 41
Alexander Ivanchenko Avatar answered May 16 '26 05:05

Alexander Ivanchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!