Lambda Hello World

I was recently checking Lambda expressions out to ensure the forthcoming JCache spec would work Ok with them. I just wanted a really simple example that worked through the different syntactical forms and ended up putting a Hello World type example myself.


/**
* Hello world!
*/
public class App {

static void print(Something something) {
System.out.println(something.doSomeThing("Hello World"));
}

@FunctionalInterface
interface Something {

String doSomeThing(String word);
}

public static void main(String[] args) {
print(new Something() {

@Override
public String doSomeThing(String word) {
return word.concat(" - it is no fun to AnonymousInnerClass");
}
});

//expression form. No return
print((String s) -> s.concat(" = it is fun to Lambda"));

//block. Need return as interface method has return.
print((String s) -> {return s.concat(" = it is fun to Lambda");});

//expression. No type required as Interface defines it.
print((s) -> s.concat(" = it is fun to Lambda"));

//creating a concrete instance of a functional interface via assignment
Something something = (s) -> s.replace("the", "thee");
System.out.println(something.doSomeThing("What the!"));

java.util.function.Predicate predicate = new

}
}

Leave a Reply