Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Lazy/functional-ish take 25 squares of integers in Java
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
You can’t perform that action at this time.