Created
July 31, 2014 19:27
-
-
Save Groostav/27c6dd6737cca02bb16b to your computer and use it in GitHub Desktop.
Example on implementing an iterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.EmpowerOperations.LinqALike.Queries; | |
import com.EmpowerOperations.LinqALike.Delegate.Func1; | |
import java.util.Iterator; | |
public class SelectQuery<TElement, TResult> implements DefaultQueryable<TResult> { | |
private final Iterable<TElement> set; | |
private final Func1<? super TElement, TResult> targetSite; | |
public SelectQuery(Iterable<TElement> set, Func1<? super TElement, TResult> targetSite) { | |
assert set != null; | |
assert targetSite != null; | |
this.set = set; | |
this.targetSite = targetSite; | |
} | |
@Override | |
public Iterator<TResult> iterator() { | |
return new SelectIterator<>(set.iterator(), targetSite); | |
} | |
private class SelectIterator<TElement, TResult> implements Iterator<TResult>{ | |
private final Iterator<TElement> baseIterator; | |
private final Func1<? super TElement, TResult> transform; | |
public SelectIterator(Iterator<TElement> baseIterator, Func1<? super TElement, TResult> transform){ | |
this.baseIterator = baseIterator; | |
this.transform = transform; | |
} | |
@Override | |
public boolean hasNext() { | |
return baseIterator.hasNext(); | |
} | |
@Override | |
public TResult next() { | |
return transform.getFrom(baseIterator.next()); | |
} | |
@Override | |
public void remove() { | |
throw new UnsupportedOperationException(); | |
} | |
} | |
} |
Notice that my outer class, implements DefaultQueryable<TElement>
, which is a version of Iterable<TElement>
(not, iter- ator ), and it has a method called iterator() that returns a SelectIterator<TElement>
. It is a little confusing with so many generics flying around.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey @Bghyun, take a look at this, maybe itl make some sense