2017-10-12 50 views
1

我有一個mapper方法,它接受來自調用它的對象的lambda函數。然後Java使用lambdas迭代映射器方法?

LambdaList<String> strings = new LambdaList<String>("May", 
"the", "force", "be", "with", "you"); 
list = strings.map(x -> x.length()); 
assert list.equals(new LambdaList<Integer>(3, 3, 5, 2, 4, 3)) 
    : "map() failed. Result is " + list + "."; 

地圖的方法將迭代雖然名單,一旦拉姆達已應用於返回一個新的列表。

/** 
    * Returns a list consisting of the results of applying the given function 
    * to the elements of this list. 
    * @param <R> The type of elements returned. 
    * @param mapper The function to apply to each element. 
    * @return The new list. 
    */ 
    public <R> LambdaList<R> map(Function<? super T, ? extends R> mapper) { 
    ArrayList<R> newList = new ArrayList<>(); 
    for(T item: this){ 
     newList.add(mapper.apply(item));  
    } 
    return new LambdaList<R>(newList); 
    } 

拉姆達列表設置如下:

class LambdaList<T> { 
    private ArrayList<T> list; 

    public LambdaList() { 
    list = new ArrayList<T>(); 
    } 


    @SafeVarargs 
    public LambdaList(T... varargs) { 
    list = new ArrayList<T>(); 
    for (T e: varargs) { 
     list.add(e); 
    } 
    } 

    private LambdaList(ArrayList<T> list) { 
    this.list = list; 
    } 

    public LambdaList<T> add(T e) { 
    ArrayList<T> newList = new ArrayList<>(); 
    newList.addAll(list); 
    newList.add(e); 
    return new LambdaList<T>(newList); 
    } 

我試着用T item: this指對象本身,但不起作用。我將如何去實施這種方法?

+0

你是怎麼定義'LambdaList'的?什麼是接口和超類? –

+0

「add」方法背後的推理是什麼?爲什麼不簡單地'list.add(e);返回這個;'? – Marvin

+1

@Marvin看起來它是一個不可改變的集合。 –

回答

1

爲了能夠編寫增強型for循環,該對象需要可迭代。

class LambdaList<T> implements Iterable<T> { ... } 

然後,您將需要實現public Iterator<T> iterator()方法,這可能會像return internalList.iterator();

+1

請注意,使用內部列表的迭代器打開了一種方法來通過'Iterator.remove()'規避列表的不可變性。 –

+0

@MikeStrobel好點 – assylias

+0

除了使用迭代器之外,還有其他方法嗎? – Carrein