What are functional interfaces used for in Java 8?

@FunctionalInterface annotation is useful for compilation time checking of your code. You cannot have more than one method besides static, default and abstract methods that override methods in Object in your @FunctionalInterface or any other interface used as a functional interface. But you can use lambdas without this annotation as well as you can override … Read more

A positive lambda: ‘+[]{}’ – What sorcery is this? [duplicate]

Yes, the code is standard conforming. The + triggers a conversion to a plain old function pointer for the lambda. What happens is this: The compiler sees the first lambda ([]{}) and generates a closure object according to §5.1.2. As the lambda is a non-capturing lambda, the following applies: 5.1.2 Lambda expressions [expr.prim.lambda] 6 The … Read more

Join/Where with LINQ and Lambda

I find that if you’re familiar with SQL syntax, using the LINQ query syntax is much clearer, more natural, and makes it easier to spot errors: var id = 1; var query = from post in database.Posts join meta in database.Post_Metas on post.ID equals meta.Post_ID where post.ID == id select new { Post = post, … Read more

Variable used in lambda expression should be final or effectively final

Although other answers prove the requirement, they don’t explain why the requirement exists. The JLS mentions why in §15.27.2: The restriction to effectively final variables prohibits access to dynamically-changing local variables, whose capture would likely introduce concurrency problems. To lower risk of bugs, they decided to ensure captured variables are never mutated.

Java 8 Lambda function that throws exception?

You’ll need to do one of the following. If it’s your code, then define your own functional interface that declares the checked exception: @FunctionalInterface public interface CheckedFunction<T, R> { R apply(T t) throws IOException; } and use it: void foo (CheckedFunction f) { … } Otherwise, wrap Integer myMethod(String s) in a method that doesn’t … Read more