Java使用lambdas迭代mapper方法?

时间:2017-10-12 10:26:06

标签: java lambda

我有一个mapper方法,它从调用它的对象接受lambda函数。

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 + ".";

然后map方法将遍历列表,并在应用lambda后返回一个新列表。

  /**
   * 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);
  }

lambda列表设置如下:

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来引用对象本身,但这并不起作用。我将如何实施此方法?

1 个答案:

答案 0 :(得分:1)

为了能够编写增强的for循环,该对象需要是可迭代的。

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

然后,您需要实施public Iterator<T> iterator()方法,该方法可能看起来像return internalList.iterator();