Class MethodReferenceExamples
java.lang.Object
net.jrodolfo.java_evolution.java08.MethodReferenceExamples
Demonstrates method references, introduced in Java 8 as a compact syntax for
lambdas that only call an existing method or constructor.
Lambdas made it easy to pass behavior, but many lambdas simply delegated to
an existing method, such as text -> Integer.parseInt(text). That
repeated information already present in the method name.
Method references solve that small readability problem. They let code say
Integer::parseInt, formatter::format,
String::compareToIgnoreCase, or User::new. The feature does
not add new behavior beyond lambdas; it makes simple delegation easier to
scan.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classSimple formatter used to demonstrate a bound instance method reference.static classSmall Java 8-style data class used by constructor reference examples. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionShows a zero-argument constructor reference withSupplier.createUsers(List<String> names) Uses a constructor reference to create a domain object from each input value.createUserWithFunction(String name) Shows that constructor references can also be assigned to functional interfaces.formatNames(List<String> names) Uses a bound instance method reference, where the receiver object already exists.parseNumbers(List<String> numbers) Uses a static method reference.sortIgnoringCase(List<String> names) Uses an unbound instance method reference, where the receiver is supplied by each stream element.
-
Constructor Details
-
MethodReferenceExamples
public MethodReferenceExamples()
-
-
Method Details
-
parseNumbers
-
formatNames
-
sortIgnoringCase
-
createUsers
Uses a constructor reference to create a domain object from each input value.- Parameters:
names- the names used to create users- Returns:
- users created with
User::new
-
createUserWithFunction
Shows that constructor references can also be assigned to functional interfaces.- Parameters:
name- the user's name- Returns:
- a user created by a
Function
-
createFormatterWithSupplier
Shows a zero-argument constructor reference withSupplier.- Returns:
- a formatter created by calling
NameFormatter::new
-