Add information on interfaces and lambdas. (#31524)

This commit is contained in:
Travis Gayle
2019-06-27 18:10:20 -04:00
committed by Randell Dawson
parent 1195a986d5
commit 5e7c9a1807

View File

@ -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:
<!-- Please add any articles you think might be helpful to read before writing the article -->