Skip to content

Instantly share code, notes, and snippets.

@dgageot
Created June 20, 2013 10:27
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 dgageot/5821722 to your computer and use it in GitHub Desktop.
Save dgageot/5821722 to your computer and use it in GitHub Desktop.
A FooBar style WTF? using Java8 lambdas
import java.util.stream.*;
public class FooFooLambdaWtf {
public static void main(String[] args) {
// prints FooBar
String fooBar = IntStream.range(1, 10).mapToObj(FooFooLambdaWtf::foorBar).collect(Collectors.joining());
System.out.println(fooBar);
// prints FooFooFooFooFooFooFooFooFoo
String fooFooFoo = IntStream.range(1, 10).mapToObj(i -> (i == 3) ? "Foo" : (i == 5) ? "Bar" : "").collect(Collectors.joining());
System.out.println(fooFooFoo);
// prints FooBar
Stream<String> fooBarStream = IntStream.range(1, 10).mapToObj(i -> (i == 3) ? "Foo" : (i == 5) ? "Bar" : "");
System.out.println(fooBarStream.collect(Collectors.joining()));
}
static String foorBar(int i) {
return (i == 3) ? "Foo" : (i == 5) ? "Bar" : "";
}
}
@fcamblor
Copy link

Another strange thing :

// prints FooBar
String fooBar = IntStream.range(1, 10).mapToObj((i) -> { String res = (i == 3) ? "Foo" : (i == 5) ? "Bar" : ""; return res; }).collect(Collectors.joining());
System.out.println(fooFooFoo);

// prints FooFooFooFooFooFooFooFooFoo
String fooFooFoo = IntStream.range(1, 10).mapToObj((i) -> { return (i == 3) ? "Foo" : (i == 5) ? "Bar" : ""; }).collect(Collectors.joining());
System.out.println(fooFooFoo);

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