Java Reference
In-Depth Information
Chapter 14. Functional programming techniques
This chapter covers
First-class citizens, higher-order functions, currying, and partial application
Persistent data structures
Lazy evaluation and lazy lists as generalizing Java streams
Pattern matching and how to simulate it in Java
Referential transparency and caching
In chapter 13 you saw how to think functionally; thinking in terms of side-effect-free methods
can help you write more maintainable code. In this chapter, we introduce more advanced
functional programming techniques. You can view this chapter as a mix of practical techniques
to apply in your codebase as well as academic information that will make you a more
knowledgeable programmer. We discuss higher-order functions, currying, persistent data
structures, lazy lists, pattern matching, caching with referential transparency, and combinators.
14.1. Functions everywhere
In chapter 13 we used the phrase functional-style programming to mean that the behavior of
functions and methods should be like that of mathematical-style functions—no side effects.
Functional-language programmers often use the phrase with more generality to mean that
functions may be used like other values: passed as arguments, returned as results, and stored in
data structures. Such functions that may be used like other values are referred to as first-class
functions . This is exactly what Java 8 adds over previous versions of Java: you may use any
method as a function value, using the :: operator to create a method reference , and lambda
expressions (for example, (int x) -> x + 1) to directly express function values. In Java 8 it's
perfectly valid to store the method Integer.parseInt in a variable by using a method reference as
follows:
Function<String, Integer> strToInt = Integer::parseInt;
14.1.1. Higher-order functions
So far we've mainly used the fact that function values are first class only in order to pass them to
Java 8 stream-processing operations (as in chapters 4 - 7 ) and to achieve the very similar effect
of behavior parameterization when we passed Apple::isGreen-Apple as a function value to
 
Search WWH ::




Custom Search