我有一個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
指對象本身,但不起作用。我將如何去實施這種方法?
你是怎麼定義'LambdaList'的?什麼是接口和超類? –
「add」方法背後的推理是什麼?爲什麼不簡單地'list.add(e);返回這個;'? – Marvin
@Marvin看起來它是一個不可改變的集合。 –