Java Reference
In-Depth Information
have methods annotated with the new-in-this-context default keyword. A default method
in an interface becomes available for use in any class that implements the interface; if you
think about it, you'll see that such methods cannot depend on instance state in a particular
class because they would have no way of referring to it at compile time.
So a functional interface is more precisely defined as one that has a single nondefault meth-
od. You can do functional-style programming in Java if you use functional interfaces and if
you restrict code in your methods to not depending on any nonfinal instance or class fields;
using default methods is one way of achieving this. The first few recipes in this chapter dis-
cuss functional interfaces.
Another Java 8 approach to this is “lambda expressions.” A lambda is an expression of a
functional interface, and can be used as data (i.e., assigned, returned, etc.). Just to give a
couple of short examples for now:
ActionListener x = ( e -> System . out . println ( "You activated " + e . getSource ());
public
public class
class RunnableLambda
RunnableLambda {
public
public static
static void
void main ( String [] args ) {
new
new Thread (() -> System . out . println ( "Hello from a thread" )). start ();
}
}
Also new in Java 8 is the notion of Stream classes. A Stream is like a pipeline that you can
feed into, fan out, collect down—like a cross between the Unix notion of pipelines and
Google's distributed programming concept of Map-Reduce, as exemplified in Hadoop , but
running in a single VM, a single program. Streams can be sequential or parallel; the latter are
designed to take advantage of the massive parallelism that is happening in hardware design
(particularly servers, where 12- and 16-core processors are popular). We discuss Stream s in
several recipes in this chapter.
Tied in with Stream s is the notion of a Spliterator , a derivative (logically, not by inherit-
ance) of the familiar Iterator , but designed for use in parallel processing. Most users will
not be expected to develop their own Spliterator and will likely not even call its methods dir-
ectly very often , so we do not discuss them in detail.
See Also
For general information on Functional Programming, see the new book Functional Thinking .
Search WWH ::




Custom Search