Carrein
Carrein

Reputation: 3361

Java iterating through a mapper method using lambdas?

I have a mapper method which accepts a lambda function from the object calling it.

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

The map method will then iterate though the list and return a new list once the lambda has been applied.

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

The lambda list is set up as below:

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

I tried using T item: this to refer to the object itself but that doesn't work. How would i go about implementing this method?

Upvotes: 1

Views: 81

Answers (1)

assylias
assylias

Reputation: 328598

To be able to write an enhanced for loop, the object needs to be iterable.

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

You will then need to implement a public Iterator<T> iterator() method, which will probably look like return internalList.iterator();.

Upvotes: 1

Related Questions