Class LambdaExamples
java.lang.Object
net.jrodolfo.java_evolution.java08.LambdaExamples
Demonstrates lambda expressions, one of the main language features introduced
in Java 8.
Before Java 8, passing behavior into a method usually meant creating an anonymous class. That made common operations such as filtering, sorting, and callbacks much more verbose than the actual idea being expressed.
Lambdas solve this by letting Java treat a small block of behavior as a
value, as long as the target type is a functional interface. They are
commonly used with interfaces such as Predicate, Comparator,
and the interfaces in java.util.function. This also made the Stream
API practical because stream operations can receive behavior directly.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceSimple functional interface used to demonstrate passing behavior into a method. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionintcalculate(int left, int right, LambdaExamples.IntegerOperation operation) Receives a custom operation as a method argument.namesWithAtLeastFourLetters(List<String> names) Filters a list by assigning a lambda expression to aPredicate.intnormalizedPositiveDifference(int left, int right) Uses a multi-statement lambda body.sortByLength(List<String> names) Sorts names using a lambda expression as aComparator.sortWithAnonymousClass(List<String> names) Sorts names with an anonymous class, the older style commonly used before Java 8 lambdas.sortWithLambda(List<String> names) Sorts names with a lambda expression, showing the shorter Java 8 replacement for a simple anonymous class.
-
Constructor Details
-
LambdaExamples
public LambdaExamples()
-
-
Method Details
-
namesWithAtLeastFourLetters
-
sortByLength
Sorts names using a lambda expression as aComparator.- Parameters:
names- the names to sort- Returns:
- a new list sorted from shortest name to longest name
-
calculate
Receives a custom operation as a method argument.- Parameters:
left- the left number used by the operationright- the right number used by the operationoperation- the behavior to apply to both numbers- Returns:
- the result produced by the operation
-
normalizedPositiveDifference
public int normalizedPositiveDifference(int left, int right) Uses a multi-statement lambda body.Single-expression lambdas can omit braces and
return. When the lambda needs more than one statement, Java requires a block body and an explicitreturnfor non-void functional interfaces.- Parameters:
left- the left number used by the operationright- the right number used by the operation- Returns:
- a normalized score
-
sortWithAnonymousClass
-
sortWithLambda
-