From 5e7c9a18075bd623ef4f955e815c8381c9c60a56 Mon Sep 17 00:00:00 2001 From: Travis Gayle Date: Thu, 27 Jun 2019 18:10:20 -0400 Subject: [PATCH] Add information on interfaces and lambdas. (#31524) --- .../english/java/lambda-expressions/index.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/guide/english/java/lambda-expressions/index.md b/guide/english/java/lambda-expressions/index.md index bffc92ce63..b1bef71aee 100644 --- a/guide/english/java/lambda-expressions/index.md +++ b/guide/english/java/lambda-expressions/index.md @@ -70,6 +70,30 @@ The terminal `collect` operation collects the stream as a list of strings. This is only one use of the Streams API used in Java 8. There are many other applications of streams utilizing other operations as seen here in the [documentation](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html). + +### Lambda Expressions and Interfaces + +Suppose you have an interface that looks something like this: + +```java +interface MathInterface { + int operation(int x, int y); +} +``` + +You can create an instance of this interface in one line using lambdas provided that the interface only has one method. + +```java +MathInterface multiply = ((int x, int y) -> x * y); +MathInterface add = ((x, y) -> x + y); +MathInterface subtraction = ((x, y) -> x - y); +MathInterface division = (((x, y) -> x / y)); + +multiply.operation(1, 2); // == 2 +add.operation(1, 2); // == 3 +``` + +Note that in some of these interfaces, we don't specify the type of each parameter. This is valid and will still work the same as specifying the types such as `(int x, int y) -> x * y`. If you specify one type, however, you must specify all types of the lambda function. #### More Information: