Lazy view of java.util.Collection in Vavr

 ̄綄美尐妖づ 提交于 2021-01-27 13:14:08

问题


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?


回答1:


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



回答2:


There is a Lazy class in vavr. You might want to use it.

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


来源:https://stackoverflow.com/questions/50988552/lazy-view-of-java-util-collection-in-vavr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!