Lazy view of java.util.Collection in Vavr



我有一个现有的api,它在返回值时使用java.util.Collection。我想在 Vavr 程序的后续部分中使用这些值,但我不想使用像List.ofAll这样的热切方法(因为我不想遍历这些Collection对象两次(。我的用例是这样的:

List<Product> filter(java.util.Collection products) {
return List.lazyOf(products).filter(pred1);
}

可能吗?

由于该方法的输入集合是 javaCollection,因此您不能依赖不可变性,因此您需要立即处理集合中包含的值。不能将其推迟到以后的时间点,因为无法保证传递的集合保持不变。

您可以通过对传递的集合的迭代进行过滤,然后将结果收集到List中,从而最大限度地减少构建的 vavrList的数量。

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

vavr 中有一个懒惰类。您可能想要使用它。

Lazy<Option<Integer>> val1 = Lazy.of(() -> 1).filter(i -> false);

最新更新