This is my example code response to Why Functional Programming in Java is Dangerous which i (somewhat harshly) commented about.
Last active
December 11, 2015 09:48
-
-
Save nicerobot/4582185 to your computer and use it in GitHub Desktop.
An example of writing `take` in Java.
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 org.nicerobot; | |
import java.util.Iterator; | |
interface Applyable<T> { | |
public T apply (Integer n); | |
} | |
public class Take { | |
public static void main (final String[] args) { | |
new Take().test(); | |
} | |
public void test () { | |
final Applyable<String> square = new Applyable<String>() { | |
@Override | |
public String apply (final Integer value) { | |
return String.format("%d\t%d", value, value * value); | |
} | |
}; | |
for (final String s : this.take(25, square)) { | |
System.out.println(s); | |
} | |
} | |
private <T> Iterable<T> take (final Integer i, final Applyable<T> f) { | |
return new Iterable<T>() { | |
@Override | |
public Iterator<T> iterator () { | |
return new Iterator<T>() { | |
private Integer n = 0; | |
@Override | |
public boolean hasNext () { | |
return this.n + 1 < i.intValue(); | |
} | |
@Override | |
public T next () { | |
return f.apply(++this.n); | |
} | |
@Override | |
public void remove () {} | |
}; | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment