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())
);
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());
are there any ways of creating an ImmutableList with instantiating the List explicitly?
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With