I have an existing api which uses java.util.Collection
when returning values. I would like to use those values in later parts of my program with Vavr but I don't want to use the eager methods like List.ofAll
(because I do not want to traverse those Collection
objects twice). My use case is something like this:
List<Product> filter(java.util.Collection products) {
return List.lazyOf(products).filter(pred1);
}
Is it possible?
Since the input collection to the method is a java Collection
, you cannot rely on immutability, so you need to process the values contained in the collection right away. You cannot defer this to a later point in time as there is no guarantee the passed collection remains unchanged.
You can minimize the number of vavr List
s built by doing the filtering on an iteration of the passed collection, then collecting the result to a List
.
import io.vavr.collection.Iterator;
import io.vavr.collection.List;
...
List<Product> filter(Collection<Product> products) {
return Iterator.ofAll(products)
.filter(pred1)
.collect(List.collector());
}