Advertisement
Guest User

You Sir, are dangerous, not Java.

a guest
Jan 20th, 2013
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. /**
  2. * Reply to http://cafe.elharo.com/programming/java-programming/why-functional-programming-in-java-is-dangerous/
  3. *
  4. * @author Christian Kohlschütter
  5. */
  6. package functional;
  7.  
  8. import java.util.Iterator;
  9.  
  10. public class FunctionalJava {
  11.  
  12. public static void main(String[] args) {
  13. print(new Take(25, new SquaresOf(new Integers())));
  14. }
  15.  
  16. static abstract class Sequence<T extends Number> implements Iterator<T>,
  17. Iterable<T> {
  18. private boolean hasNext = true;
  19. protected Iterator<T> in;
  20.  
  21. protected Sequence() {
  22. this(null);
  23. }
  24.  
  25. protected Sequence(final Iterator<T> in) {
  26. this.in = in;
  27. }
  28.  
  29. @Override
  30. public Iterator<T> iterator() {
  31. return this;
  32. }
  33.  
  34. @Override
  35. public boolean hasNext() {
  36. return hasNext && (in == null || in.hasNext());
  37. }
  38.  
  39. @Override
  40. public abstract T next();
  41.  
  42. @Override
  43. public void remove() {
  44. throw new UnsupportedOperationException();
  45. }
  46.  
  47. protected void endOfSequence() {
  48. hasNext = false;
  49. }
  50. }
  51.  
  52. static final class Integers extends Sequence<Integer> {
  53. private int value;
  54.  
  55. Integers() {
  56. this(1);
  57. }
  58.  
  59. Integers(final int startValue) {
  60. this.value = startValue;
  61. }
  62.  
  63. @Override
  64. public Integer next() {
  65. return value++;
  66. }
  67. }
  68.  
  69. static final class Take extends Sequence<Integer> {
  70. private int limit;
  71.  
  72. Take(final int limit, final Iterator<Integer> in) {
  73. super(in);
  74. this.limit = limit;
  75. }
  76.  
  77. @Override
  78. public Integer next() {
  79. try {
  80. return in.next();
  81. } finally {
  82. if (--limit == 0) {
  83. endOfSequence();
  84. }
  85. }
  86. }
  87.  
  88. }
  89.  
  90. static final class SquaresOf extends Sequence<Integer> {
  91. SquaresOf(final Iterator<Integer> in) {
  92. super(in);
  93. }
  94.  
  95. @Override
  96. public Integer next() {
  97. final int v = in.next();
  98. return v * v;
  99. }
  100. }
  101.  
  102. static void print(final Iterator<?> it) {
  103. System.out.print('(');
  104. if (it.hasNext()) {
  105. System.out.print(it.next());
  106. while (it.hasNext()) {
  107. System.out.print(' ');
  108. System.out.print(it.next());
  109. }
  110. }
  111. System.out.println(')');
  112. }
  113. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement