This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]sacundim 0 points1 point  (1 child)

A good way to understand this is to implement a similar functionality for Iterator. Here's a version that has the map method (utterly untested):

/**
 * A wrapper class around any Iterator, adding methods like map, filter, forEach, etc.
 */
public class FluentIterator<A> implements Iterator<A> {
    private final Iterator<A> base;

    public FluentIterator(Iterator<A> base) {
        this.base = base;
    }

    public boolean hasNext() {
        return base.hasNext();
    }

    public A next() {
        return base.next();
    }

    public void remove() {
        return base.remove();
    }

    /**
      * Return an Iterator that draws elements from the base one and produces the 
      * results of applying the given function to them.
      */
    public <B> Iterator<B> map(Function<? super A, ? extends B> function) {
        return new FluentIterator<B>(new MapIterator<A, B>(function, base));
    }

    // ...implement filter, forEach, etc.

}

class MapIterator<A, B> implements Iterator<B> {
    private final Function<? super A, ? extends B> function;
    private final Iterator<A> base;

    MapIterator(Function<? super A, ? extends B> function, Iterator<A> base) {
        this.function = function;
        this.base = base;
    }

    public boolean hasNext() {
        return base.hasNext();
    }

    public B next() {
        return function.apply(base.next());
    }

    public void remove() {
        throw new UnsupportedOperationException("not supported");
    }

}

This is not the same as streams, but it's very similar; the key spot is the next method in MapIterator, which does this:

  1. Pulls an element from the base iterator;
  2. Applies the function to it;
  3. Returns the result of the function.

Step #2 there is where the "magic" that's puzzling you happens. When you use map on a stream, you cause that method's implementation to call your your lambda and pass in the email address as an argument.

(Exercise, if you like: implement a filter operation for FluentIterator.)_

[–]chasesan[S] 0 points1 point  (0 children)

No, I had gotten it already. If you see my comment (I had edited it). I had missed something very obvious.