Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Reply to http://cafe.elharo.com/programming/java-programming/why-functional-programming-in-java-is-dangerous/
- *
- * @author Christian Kohlschütter
- */
- package functional;
- import java.util.Iterator;
- public class FunctionalJava {
- public static void main(String[] args) {
- print(new Take(25, new SquaresOf(new Integers())));
- }
- static abstract class Sequence<T extends Number> implements Iterator<T>,
- Iterable<T> {
- private boolean hasNext = true;
- protected Iterator<T> in;
- protected Sequence() {
- this(null);
- }
- protected Sequence(final Iterator<T> in) {
- this.in = in;
- }
- @Override
- public Iterator<T> iterator() {
- return this;
- }
- @Override
- public boolean hasNext() {
- return hasNext && (in == null || in.hasNext());
- }
- @Override
- public abstract T next();
- @Override
- public void remove() {
- throw new UnsupportedOperationException();
- }
- protected void endOfSequence() {
- hasNext = false;
- }
- }
- static final class Integers extends Sequence<Integer> {
- private int value;
- Integers() {
- this(1);
- }
- Integers(final int startValue) {
- this.value = startValue;
- }
- @Override
- public Integer next() {
- return value++;
- }
- }
- static final class Take extends Sequence<Integer> {
- private int limit;
- Take(final int limit, final Iterator<Integer> in) {
- super(in);
- this.limit = limit;
- }
- @Override
- public Integer next() {
- try {
- return in.next();
- } finally {
- if (--limit == 0) {
- endOfSequence();
- }
- }
- }
- }
- static final class SquaresOf extends Sequence<Integer> {
- SquaresOf(final Iterator<Integer> in) {
- super(in);
- }
- @Override
- public Integer next() {
- final int v = in.next();
- return v * v;
- }
- }
- static void print(final Iterator<?> it) {
- System.out.print('(');
- if (it.hasNext()) {
- System.out.print(it.next());
- while (it.hasNext()) {
- System.out.print(' ');
- System.out.print(it.next());
- }
- }
- System.out.println(')');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement