简体   繁体   English

如何生成功能支持的列表?

[英]How can I generate a List backed by a Function?

I have a function myFunction of Function<Integer, T> , and I want to construct an object mylist of size size , implementing List<T> (or maybe some kind of immutable list interface), backed by the function, in the sense that mylist.get(i) == myFunction.apply(i) . 我有一个函数myFunction ,该函数为Function<Integer, T> ,我想构造一个大小为size的对象mylist ,实现List<T> (或某种不可变的列表接口),并以该函数为后盾, mylist.get(i) == myFunction.apply(i)

I can do this manually, but is there some (Guava) code which does the same? 我可以手动执行此操作,但是是否有一些(Guava)代码具有相同的功能?

Just use java.util.AbstractList : 只需使用java.util.AbstractList

 new AbstractList<T>() {
   public T get(int i) {
     Preconditions.checkElementIndex(i, size);
     return function.apply(i);
   }
   public int size() {
     return size;
   }
 }

The result would not necessarily be immutable, since the function output could vary. 结果不一定是不变的,因为函数输出可能会发生变化。 In all likelihood, you could get rid of the Function entirely, and just write the implementation of the Function in your AbstractList implementation. 您很可能会完全摆脱Function ,而只需在AbstractList实现中编写Function的实现即可。

Perhaps instead of a list you should consider an Iterator<T> . 也许应该考虑使用Iterator<T>代替列表。

// Example simple Function that returns each element from the array.
static class Function<T> {
    final T[] t;
    Function(T[] t) {
        this.t = t;
    }
    T apply (Integer i) {
        return t[i];
    }
}

static class FunctionIterator<T> implements Iterator<T> {
    final Function<T> f;
    Integer i;
    Integer to;
    Integer step;

    FunctionIterator(Function<T> f, Integer from, Integer to) {
        this.f = f;
        if ( to > from ) {
            step = 1;
            i = from;
            this.to = to;
        } else {
            step = -1;
            i = to;
            this.to = from;
        }
    }

    @Override
    public boolean hasNext() {
        return i != to + step;
    }

    @Override
    public T next() {
        T next = f.apply(i);
        i += step;
        return next;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException("Not supported.");
    }
}

This code offers an Iterator . 这段代码提供了一个Iterator You can make an Iterable from it quite easily. 您可以很容易地从中进行Iterable Here is an excellent and neat example of how to do it. 是一个很好的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM