Java Reference
In-Depth Information
gives you a way to pass executable code as an argument to a method. This greatly enhances
the expressive power of Java.
To illustrate the process, this project creates three string functions that perform the fol-
lowing operations: reverse a string, reverse the case of letters within a string, and replace
spaces with hyphens. These functions are implemented as lambda expressions of the func-
tional interface
StringFunc
. They are then passed as the first argument to a method called
changeStr( )
. This method applies the string function to the string passed as the second
argument to
changeStr( )
and returns the result. Thus,
changeStr( )
can be used to apply a
variety of different string functions.
1
. Create a file called
LambdaArgumentDemo.java
.
2
. To the file, add the functional interface
StringFunc
, as shown here:
This interface defines the method
func( )
, which takes a
String
argument and returns
a
String
. Thus,
func( )
can act on a string and return the result.
3
. Begin the
LambdaArgumentDemo
class, as shown here, by defining the
changeStr(
)
method:
As the comment indicates,
changeStr( )
has two parameters. The type of the first is
StringFunc
. This means it can be passed a reference to any
StringFunc
instance.
Thus, it can be passed a reference to an instance created by a lambda expression that
is compatible with
StringFunc
. The string to be acted on is passed to
s
. The resulting
string is returned.
4
. Begin the
main( )
method, as shown here: