This question already has answers here:
How to avoid applied lazily Lists.transform in guava?

(3个答案)


5年前关闭。





转换时可以依靠顺序吗?

public class DtoFunc implements Function<Entity,DTO>{

    Entity previousEntity;

    @Override
    public DTO apply(Entity entity){
       DTO dto = new DTO();
       // do transforming

       previousEntity = entity;
       return dto;
    }
}


如您所见,我将状态存储在函数中,并且依靠它,当我调用Lists.transform(entityList,new DtoFunc())时,它将相应地进行转换
它按顺序转换吗?我可以依靠吗?

正确答案:转换顺序取决于对转换列表的访问,因为转换是惰性的。函数必须是无状态的,因为Guava不是线程安全的。

最佳答案

从JavaDoc中的Lists.transform


该函数延迟应用,在需要时调用。


即如果您这样做:

List<Foo> fooList = newArrayList<Foo>();
// ...
List<Bar> barList = Lists.transform(fooArrayList, fooToBarFunction);
barList.get(5);


然后番石榴将从fooList获取索引为5的元素,将fooToBarFunction应用于该元素,并将其返回给调用者。具有其他索引的元素将不会被触及。

如果fooList不是RandomAccessList,则结果可能会不同:

List<Foo> fooList = newLinkedList<Foo>();
// ...
List<Bar> barList = Lists.transform(fooArrayList, fooToBarFunction);
barList.get(5);


该调用将通过从元素0到元素5进行迭代来访问索引为5的元素,并可能在其间的每个元素上应用转换函数。

因此,不能保证变换的顺序。但是,如果您可以控制返回列表的访问顺序,并且源列表的类型为RandomAccess,则fooToBarFunction的调用顺序与结果列表上的调用顺序完全相同。这从文档中得出,当您访问返回的列表时,该函数被延迟应用,并保证返回的列表实现了RandomAccess(如果源列表确实如此)。

关于java - Guava Lists.transform可以保证订单吗? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26295123/

10-11 19:18