Java Reference
In-Depth Information
Method References
Recall that we can think of lambda expressions as methods that don't have names.
Now, consider this lambda expression:
// In real code this would probably be shorter because of type inference
( MyObject myObj ) -> myObj . toString ()
This will be autoconverted to an implementation of a @FunctionalInterface that
has a single nondefault method that takes a single MyObject and returns String .
However, this seems like excessive boilerplate, and so Java 8 provides a syntax for
making this easier to read and write:
MyObject: : toString
This is a shorthand, known as a method reference , that uses an existing method as a
lambda expression. It can be thought of as using an existing method, but ignoring
the name of the method, so it can be can used as a lambda, and autoconverted in the
usual way.
m
Functional Programming
Java is fundamentally an object-oriented lanaguage. However, with the arrival of
lambda expressions, it becomes much easier to write code that is closer to the func‐
tional approach.
e
There's no single definition of exactly what constitutes a func‐
tional language —but there is at least a consensus that it should
at least contain the ability to represent a function as a value
that can be put into a variable.
Java has always (since version 1.1) been able to represent functions via inner classes,
but the syntax was complex and lacking in clarity. Lambda expressions greatly sim‐
plify that syntax, and so it is only natural that more developers will be seeking to use
aspects of functional programming in their Java code, now that it is considerably
easier to do so.
The first taste of functional programming that Java developers are likely to
encounter are three basic idioms that are remarkably useful:
map( The map idiom is used with lists, and list-like containers. The idea is that a
function is passed in that is applied to each element in the collection, and a new
collection is created—consisting of the results of applying the function to each
element in turn. This means that a map idiom converts a collection of one type
to a collection of potentially a different type.
Search WWH ::




Custom Search