Created
January 20, 2013 15:21
-
-
Save davetron5000/4579317 to your computer and use it in GitHub Desktop.
Lazy/functional-ish take 25 squares of integers in Java
This file contains 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
import java.util.*; | |
public class Functional { | |
public static void main(String args[]) { | |
System.out.println(take(25,squaresOf(integers()))); | |
} | |
private static List<Integer> take(int numToTake, Iterable<Integer> seq) { | |
List<Integer> results = new ArrayList<Integer>(); | |
Iterator<Integer> iterator = seq.iterator(); | |
for(int i=0;i<numToTake;i++) { | |
if (iterator.hasNext()) { | |
results.add(iterator.next()); | |
} | |
} | |
return results; | |
} | |
private static Iterable<Integer> squaresOf(final Iterable<Integer> seq) { | |
return new Iterable<Integer>() { | |
public Iterator<Integer> iterator() { | |
return new SquaringIterator(seq.iterator()); | |
} | |
}; | |
} | |
private static Iterable<Integer> integers() { | |
return new Iterable<Integer>() { | |
public Iterator<Integer> iterator() { | |
return new IntegersIterator(); | |
} | |
}; | |
} | |
private static class SquaringIterator implements Iterator<Integer> { | |
private Iterator<Integer> original; | |
public SquaringIterator(Iterator<Integer> iter) { | |
original = iter; | |
} | |
public boolean hasNext() { | |
return original.hasNext(); | |
} | |
public Integer next() { | |
int value = original.next(); | |
return value * value; | |
} | |
public void remove() { | |
original.remove(); | |
} | |
} | |
private static class IntegersIterator implements Iterator<Integer> { | |
private int nextInt = 0; | |
public boolean hasNext() { | |
return nextInt < Integer.MAX_VALUE; | |
} | |
public Integer next() { | |
if (!hasNext()) { | |
throw new NoSuchElementException(); | |
} | |
nextInt++; | |
return nextInt - 1; | |
} | |
public void remove() { | |
throw new UnsupportedOperationException(); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment