Skip to content

Instantly share code, notes, and snippets.

@dszakallas
Last active January 9, 2018 10:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dszakallas/bd4637fe69619481b923626382de3da0 to your computer and use it in GitHub Desktop.
Save dszakallas/bd4637fe69619481b923626382de3da0 to your computer and use it in GitHub Desktop.
Java, Not even once

Endless streams

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

why

@laszlovandenhoek
Copy link

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 ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment