public class Main {
public static void main(String[] args) throws InterruptedException {
Enumerable<String> query =
new Enumerable<Integer>(
iterate(
0,
new Func1<Integer, Integer>(){
public Integer _(Integer arg0) {
return arg0 + 1;
}
}
)
)
.take(10)
.select(
new Func1<Integer, String>() {
public String _(Integer arg0) {
return "Hello, World!!" + (arg0 * 2);
}
}
);
for (String s : query) {
System.out.println(s);
Thread.sleep(1000);
}
}
private static <T> Iterable<T> iterate(final T initialValue, final Func1<T, T> func) {
final class IteratorImpl extends IteratorAdaptor<T> {
private T next = initialValue;
@Override
public boolean hasNext() {
return true;
}
@Override
public T next() {
T next = this.next;
this.next = func._(next);
return next;
}
}
return new IteratorImpl().asIterable();
}
}
class IteratorAdaptor<T> implements Iterator<T> {
@Override
public boolean hasNext() {
return false;
}
@Override
public T next() {
return null;
}
@Override
public void remove() {
}
public Iterable<T> asIterable() {
final IteratorAdaptor<T> _this = this;
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return _this;
}
};
}
}
interface Func0<TResult> {
TResult _();
}
interface Func1<T, TResult> {
TResult _(T arg0);
}
class Enumerable<T> implements Iterable<T> {
private Iterable<T> itr;
public Enumerable(Iterable<T> itr) {
this.itr = itr;
}
public <TResult> Enumerable<TResult> select(final Func1<T, TResult> func) {
final Enumerable<T> _this = this;
final class IteratorImpl extends IteratorAdaptor<TResult> {
private Iterator<T> itr = _this.itr.iterator();
@Override
public boolean hasNext() {
return itr.hasNext();
}
@Override
public TResult next() {
return func._(itr.next());
}
}
return new Enumerable<TResult>(new IteratorImpl().asIterable());
}
public Enumerable<T> take(final int count) {
final Enumerable<T> _this = this;
final class IteratorImpl extends IteratorAdaptor<T> {
private int index;
private Iterator<T> itr = _this.itr.iterator();
@Override
public boolean hasNext() {
return index++ < count ? itr.hasNext() : false;
}
@Override
public T next() {
return itr.next();
}
}
return new Enumerable<T>(new IteratorImpl().asIterable());
}
@Override
public Iterator<T> iterator() {
return this.itr.iterator();
}
}
2009年9月10日木曜日
JavaでLINQ02
変数はfinalにすればメンバに持たせる必要はないらしい。Adaptorクラスを分割。
登録:
コメントの投稿 (Atom)
0 件のコメント:
コメントを投稿