Disclaimer: This is a satire, and not meant to be taken any more seriously than Java itself. It is not about Java 8 streams. This satire just shows how easy is to define a very complex endless stream functionally in Java using lambdas.
In Scala:
def naturals: Stream[Int] = 0 #:: naturals.map(_ + 1)
naturals.take(5).foreach(println)
// 0
// 1
// 2
// 3
// 4
In Java (if the language were halfway sane):
Function<Void, Stream<Integer>> n = (Void) -> Stream.cons(
(Void _0) -> 0,
(Void _0) -> n.andThen(x -> x.map(y -> y + 1)).apply(null));
Stream<Integer> naturals = n.apply(null);
naturals.take(5).foreach(x -> System.out.println(x));
but it gives the error: The local variable n may not have been initialized
,
for the n
inside the lambda.
In Real Java:
@SuppressWarnings("rawtypes")
final Function[] _n = { null };
@SuppressWarnings("unchecked")
Function<Void, Stream<Integer>> __n = _n[0];
__n = (Void) -> Stream.cons(
(Void _0) -> 0,
((Void _0) -> {
@SuppressWarnings("unchecked")
Stream<Integer> f = ((Function<Void, Stream<Integer>>)_n[0])
.andThen(x -> x.map(y -> y + 1)).apply(null);
return f;
})
);
_n[0] = __n;
Stream<Integer> naturals = __n.apply(null);
naturals.take(5).foreach(x -> System.out.println(x));
// 0
// 1
// 2
// 3
// 4
No love lost on Java here, but on a serious note for those who are stuck on Java for reasons, and actually want to do this in a way as sane as possible:
IntStream.iterate(1, (n) -> n + 1).limit(5).forEach(System.out::println);
Not quite as elegant or "Functional" as the Scala example, but plenty serviceable until you can switch over ;)