Download Full Learning Java Functional Programming 1st Edition Reese Richard M PDF All Chapters
Download Full Learning Java Functional Programming 1st Edition Reese Richard M PDF All Chapters
com
https://textbookfull.com/product/learning-java-functional-
programming-1st-edition-reese-richard-m/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/learning-network-programming-with-
java-1st-edition-reese-richard-m/
textboxfull.com
https://textbookfull.com/product/natural-language-processing-with-
java-community-experience-distilled-1st-edition-reese-richard-m/
textboxfull.com
https://textbookfull.com/product/ejb-3-1-cookbook-1st-edition-m-reese-
richard/
textboxfull.com
https://textbookfull.com/product/java-for-data-science-1st-edition-
reese/
textboxfull.com
Learning Java Beginning programming with java for dummies
First Edition John Bach
https://textbookfull.com/product/learning-java-beginning-programming-
with-java-for-dummies-first-edition-john-bach/
textboxfull.com
https://textbookfull.com/product/learning-java-an-introduction-to-
real-world-programming-with-java-marc-loy/
textboxfull.com
https://textbookfull.com/product/learning-java-an-introduction-to-
real-world-programming-with-java-5th-edition-marc-loy/
textboxfull.com
https://textbookfull.com/product/modern-java-in-action-lambdas-
streams-functional-and-reactive-programming-raoul-gabriel-urma/
textboxfull.com
Richard M Reese
BIRMINGHAM - MUMBAI
Learning Java Functional Programming
All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
ISBN 978-1-78355-848-3
www.packtpub.com
Credits
Reviewers Proofreader
Jose Luis Ordiales Coscia Safis Editing
David Greco
Hossein Kazemi Indexer
Rekha Nair
Amar Potghan
Graphics
Commissioning Editor
Jason Monteiro
Veena Pagare
Abhinash Sahu
Acquisition Editor
Vivek Anantharaman Production Coordinator
Aparna Bhagat
Technical Editor
Prajakta Mhatre
Copy Editor
Charlotte Carneiro
About the Author
Richard M Reese has worked in both industry and academics. For 17 years, he
worked in the telephone and aerospace industries, serving in several capacities,
including research and development, software development, supervision, and
training. He currently teaches at Tarleton State University, where he has the
opportunity to draw on his years of industry experience to enhance his teaching.
Richard has written several Java books and a C pointer book. He uses a concise and
easy-to-follow approach to the topics at hand. His Java books have addressed EJB
3.1, updates to Java 7 and 8, certification, jMonkeyEngine, and Natural Language
Processing.
Richard would like to thank his daughter, Jennifer, for her numerous
reviews and contributions; his wife, Karla, for her continued
support; and the staff at Packt for their work in making this
a better book.
About the Reviewers
He has more than 7 years of experience working in backend development with Java
and other JVM languages.
Did you know that Packt offers eBook versions of every book published, with PDF
and ePub files available? You can upgrade to the eBook version at www.PacktPub.
com and as a print book customer, you are entitled to a discount on the eBook copy.
Get in touch with us at service@packtpub.com for more details.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital
book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser
[i]
Table of Contents
Referential transparency 37
Closure in Java 38
Currying 40
Lambda expressions revisited 43
Java 8 type inference 44
Exception handling in lambda expressions 46
Functional interfaces revisited 47
Creating a functional interface 47
Common functional interfaces 47
Function-type functional interfaces 48
Predicate-type functional interfaces 49
Consumer-type functional interfaces 50
Supplier-type functional interfaces 51
Operator-type functional interfaces 51
Summary 53
Chapter 3: Function Composition and Fluent Interfaces 55
Introduction to function composition 56
Creating composite functions prior to Java 8 56
Creating composite functions in Java 8 58
Using the Function interface for function composition 59
Using the Functional interface to supplement methods 60
Passing instances of the Functional interface 61
Fluent interfaces 64
Fluent interfaces in Java 8 64
Method chaining and cascading 65
Contrasting method cascading and fluent interfaces 67
Creating and using fluent interfaces 68
Using fluent interfaces to hide older interfaces/classes 72
Using fluent interfaces with the Properties class 74
Extending fluent interfaces 76
Default methods and functions 80
Static default methods 81
Default methods in Java 8 81
Multiple inheritance in Java 8 83
Summary 84
Chapter 4: Streams and the Evaluation of Expressions 85
The Stream class and its use 86
Intermediate and terminal methods 88
Creating streams 89
Fixed length streams 90
[ ii ]
Table of Contents
Infinite streams 90
Using the iterate method to create an infinite stream 91
Using the generate method to create an infinite stream 94
Using the Stream class methods 95
Filter methods 96
Using the filter method 97
Using the skip method 98
Sorting streams 99
Mapping methods 100
Understanding the mapping operation 100
Implementing the map-reduce paradigm 101
Using the flatmap method 103
Lazy and eager evaluation 106
Stream and concurrent processing 109
Understanding non-inference 110
Understanding stateless operations 111
Understanding side effects 112
Understanding the ordering 113
Summary 114
Chapter 5 Recursion Techniques in Java 8 117
Recursive data structures 118
Types of recursion 120
Using direct recursion 120
Head and tail recursion 121
Understanding recursion 123
The Node class 124
Using head recursion 126
Using tail recursion 127
Using the head and tail recursion 128
Creating a recursive solution based on a formula 129
Converting an iterative loop to a recursive solution 131
Merging two lists 132
Understanding the program stack 133
Recursive lambda expressions 137
Common problems found in recursive solutions 137
Absence of a base case 138
Using static or instance variables 138
Using the pre- and post-increment operators 139
Recursion implementation techniques 139
Using a wrapper method 140
Using short circuiting 140
[ iii ]
Table of Contents
[ iv ]
Table of Contents
[v]
Table of Contents
[ vi ]
Preface
With the introduction of Java 8, many functional programming techniques have been
added to the language. However, functional programming may seem unfamiliar to
developers who are used to using imperative and object-oriented techniques. The
new additions to Java 8 offer the opportunity to develop more maintainable and
robust applications than that offered by earlier versions of Java.
Chapter 3, Function Composition and Fluent Interfaces, addresses how to use functional
composition. Also covered are fluent interfaces and the use of default methods.
Chapter 4, Streams and the Evaluation of Expressions, covers the basics of their creation
and use. Streams are an important addition to Java.
[ vii ]
Preface
Chapter 6, Optional and Monads, covers the use and the nature of monads in creating
fluent interfaces and producing resilient code. The Optional class provides a better
way of working with missing data.
Chapter 8, Refactoring, Debugging, and Testing, demonstrates how these tools have
been affected by the new functional programming techniques and how IDEs
support them. These are valuable tools in the development process.
Conventions
In this book, you will find a number of text styles that distinguish between different
kinds of information. Here are some examples of these styles and an explanation of
their meaning.
[ viii ]
Preface
Code words in text are shown are follows: "As you may remember, the forEach
method accepts a lambda expression which matches the Consumer interface's
accept method."
New terms and important words are shown in bold. Words that you see on the screen,
for example, in menus or dialog boxes, appear in the text like this: "There is the text
form as entered by the user such as: drop Axe."
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or disliked. Reader feedback is important for us as it
helps us develop titles that you will really get the most out of.
If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide at www.packtpub.com/authors.
[ ix ]
Preface
Customer support
Now that you are the proud owner of a Packt book, we have a number of things
to help you to get the most from your purchase.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in the text or
the code—we would be grateful if you could report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you find any errata, please report them by visiting http://www.packtpub.
com/submit-errata, selecting your book, clicking on the Errata Submission Form
link, and entering the details of your errata. Once your errata are verified, your
submission will be accepted and the errata will be uploaded to our website or
added to any list of existing errata under the Errata section of that title.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all
media. At Packt, we take the protection of our copyright and licenses very seriously.
If you come across any illegal copies of our works in any form on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.
We appreciate your help in protecting our authors and our ability to bring you
valuable content.
[x]
Preface
Questions
If you have a problem with any aspect of this book, you can contact us at
questions@packtpub.com, and we will do our best to address the problem.
[ xi ]
Getting Started with
Functional Programming
Functional programming languages have been used successfully for decades and
present a different and often more elegant way of expressing the program logic.
Functional languages, such as Lisp, Clojure, or Haskell, incorporate techniques that
may seem odd and hard to follow by programmers who are used to imperative
programming techniques.
A language such as Java, while not initially developed with a functional orientation,
can incorporate functional techniques. This is the major change to the language
made with the release of Java 8. Java now incorporates imperative, procedural,
object-oriented, and functional techniques.
[1]
Getting Started with Functional Programming
This is followed by the support Java 8 provides for functional programming, including:
• Lambda expressions
• Default methods
• Functional interface
• Method and constructor references
• Collections
• Functions
• Function composition
• Fluent interfaces
[2]
Chapter 1
Each of these concepts will be introduced in the following sections. We will explore
the nature of each concept, explain why it is important, and when practical provide
simple examples using Java.
Functions
Functions are the foundation of functional programming languages. They play a
central role in supporting other functional programming concepts. In this section,
we will introduce many of the terms used to describe functions including high-order,
first-class, and pure functions. The concepts of closure and currying will also
be explained.
High-order functions depend upon the existence of first-class functions. They are
functions that either:
Java 8 has introduced the concept of lambda expressions to the language. These are
essentially anonymous functions that can be passed to and returned from functions.
They can also be assigned to a variable. The basic form of a lambda expression
follows where a parameter, such as x, is passed to the body of the function. The
lambda operator, ->, separates the parameter from the body. This function is
passed a value, which is multiplied by two and then returned, as follows:
x -> 2 * x
In this lambda expression, it is assumed that an integer is passed and that integer is
returned. However, the data type is not restricted to an integer as we will see later.
In the following lambda expression, an argument is passed and nothing is returned:
x->System.out.println(x)
[3]
Getting Started with Functional Programming
Lambda expressions must be used in the proper context. It would not be appropriate
to pass a lambda expression, which returns a value to a method, to a function that
cannot use the returned value.
We can use the previous expression in many places that expect a single value being
passed and nothing to be returned as shown next. In the following example, an array
of integers is converted to a list. The lambda expression is then used as an argument
to the List class's forEach method, which displays each element of the list. The
forEach method applies the lambda expression to each element in the list, avoiding
having to create an explicit loop to achieve the same effect:
Integer arr[] = {1,2,3,4,5};
List<Integer> list = Arrays.asList(arr);
list.forEach(x->System.out.println(x));
The output will list the numbers one to five on separate lines.
A pure function is a function that has no side effects. This means that memory
external to the function is not modified, IO is not performed, and no exceptions are
thrown. With a pure function, when it is called repeatedly with the same parameters,
it will return the same value. This is called referential transparency.
• The function can be called repeatedly with the same argument and get the
same results. This enables caching optimization (memorization).
• With no dependencies between multiple pure functions, they can be
reordered and performed in parallel. They are essentially thread safe.
[4]
Chapter 1
• Pure function enables lazy evaluation as discussed later in the Strict versus
non-strict evaluation section. This implies that the execution of the function
can be delayed and its results can be cached potentially improving the
performance of a program.
• If the result of a function is not used, then it can be removed since it does
not affect other operations.
There are several other terms associated with functions, such as the term closure.
This refers to a function passed around along with its environment. The environment
consists of the variables it uses. Java 8 supports a form of closure, and will be
illustrated in Chapter 2, Putting the Function in Functional Programming.
f ( x, y ) = x + y
f ( 3, 4 ) = 3 + 4
f ( 3, y ) = 3 + y
g ( y) = 3 + y
f ( 3, y ) = g ( y ) = 3 + y
We reduced the number of arguments from two to one. Using a value of 4 for
y yields the original result of 7. The process of currying, and partially applying
functions, permit high-order functions to be used more effectively. This will
become clearer in Chapter 2, Putting the Function in Functional Programming.
[5]
Getting Started with Functional Programming
Function composition
Imperative programming places emphasis on a step-by-step process to implement
an application. This is typified by a logical set of steps where code is executed using
basic control constructs and is often encapsulated in functions or procedures.
Functional programming places more emphasis on how these functions are arranged
and combined. It is this composition of functions, which typifies a functional style of
programming. Functions are not only used to organize the execution process, but are
also passed and returned from functions. Often data and the functions acting on the
data are passed together promoting more capable and expressive programs.
We will illustrate this technique using the Function interface as defined in the java.
util.function package. This interface possesses a compose and andThen methods.
Both of these methods return a composed function.
The compose method will execute the function passed to it first, and then uses its
result with the function the compose method is executed against. The andThen
method will execute the first function and then execute the function passed as an
argument to the andThen method.
The next code sequence demonstrates the compose method, which is passed as a
function to take the absolute value of a number. The absThenNegate variable is
assigned a function that will also negate the number. This variable is declared as a
Function type, which means that the function assigned to it expects to be passed as
an integer and returns an integer.
This function will execute the argument of the compose method and the Math class's
abs method first, against some value, and then apply the negateExact method
to this result. In other words, it will take the absolute value of a number and then
negate it. Both of these methods are expressed as method references, which are new
to Java 8. A method reference consist of the class name followed by a set of double
colons, and then a method name providing a simpler form of method invocation:
Function<Integer,Integer>absThenNegate =
((Function<Integer,Integer>)Math::negateExact)
.compose(Math::abs);
This is illustrated with the following sequence. The Function interface's apply
method is used to invoke the composed function:
System.out.println(absThenNegate.apply(-25));
System.out.println(absThenNegate.apply(25));
[6]
Chapter 1
Both of these statements will display a -25. In the first statement, the absolute value
of a -25 is obtained and then negated. The second statement works the same way
except its argument is +25.
The negateThenAbs variable that follows, illustrates the andThen method. The
function used as an argument to the andThen method is applied after the first function
is executed. In this case, the negateExact method is executed first and then the abs
function is applied:
Function<Integer,Integer>negateThenAbs =
((Function<Integer,Integer>)Math::negateExact)
.andThen(Math::abs);
System.out.println(negateThenAbs.apply(-25));
System.out.println(negateThenAbs.apply(25));
We could have obtained the same results with a series of imperative statements.
However, this does not result in as much flexibility as can be obtained using
function composition. The ability to pass functions will provide the enhanced
flexibility. We will postpone a detailed discussion of this approach until Chapter 3,
Function Composition and Fluent Interfaces.
Fluent interfaces
Fluent interfaces constitute a way of composing expressions that are easier to write
and understand. A fluent interface is often implemented using method chaining,
sometimes called method cascading, where the returned value is used again in the
same context.
In Java 8, the use of fluent interfaces is found in numerous places. We will illustrate
this style with an example using the new Date and Time API.
Suppose we want to calculate a new date that is 2 years in the future, minus 1 month
plus 3 days. We can use the following code sequence to achieve this result. The
LocalDate class's method now returns an instance of the LocalDate class representing
the current date. This date is the base for creating a new day called futureDate:
LocalDate today = LocalDate.now();
LocalDate futureDate = today.plusYears(2);
futureDate = futureDate.minusMonths(1);
futureDate = futureDate.plusDays(3);
System.out.println(today);
System.out.println(futureDate);
[7]
Getting Started with Functional Programming
Contrast this with the next code sequence, which takes advantage of the APIs fluent
interface and produces the same output:
LocalDatefutureDate = LocalDate.now()
.plusYears(2)
.minusMonths(1)
.plusDays(3);
The code flow is easy to read and flows in a more natural way. You will see repeated
usage of fluent interfaces in the book. Streams use this approach consistently.
With non-strict evaluation, they are not evaluated until necessary. Non-strict
evaluation is sometimes called lazy evaluation. However, these terms are not
always strict synonyms. Non-strict evaluation is concerned with the semantics of the
expression, while lazy evaluation deals more with how the expression is evaluated.
[8]
Random documents with unrelated
content Scribd suggests to you:
EXTENT OF THE FRUITFUL PERIOD.
The cessation of the menses, as I have remarked, is generally the
limit of the period of child-bearing; but this rule, like all others, has
its exceptions.
Bartholomew Mosse, according to Dr. Guy, mentions four cases of
women pregnant in their fifty-first year, and Dr. Labatt, of Dublin,
one; Knebel and Lamatte each one in the fifty-second year;
Bartholomew Mosse and Knebel each one in the fifty-fourth year; a
case of pregnancy at the same age (that of Mrs. Ashley) is also related
in the Edinburgh Annual Register for 1816, in the French accusation,
in which the succession to an estate was disputed on the ground of
the mother being fifty-eight years old when the child was born, and
the decision was given in favor of the fact.
Pliny, Valescus de Tarenta, and Marra, of Venice, record cases of
pregnancy at sixty.
Capuron, a French author, states that a woman of sixty-three was
generally believed in Paris to have given birth to a daughter.
Dr. Beck, of Albany, quotes a case from the Boston Medical and
Surgical Journal, of a woman at White Hall, New York, becoming a
mother at sixty-four.
A writer in the Edinburgh Medical and Surgical Journal, Mr.
Robertson, states that out of 10,000 pregnant females registered at
the Manchester Lying-in Hospital, 436 were upward of forty-six
years of age. Of these there were—
397 from 40 to 46
13 in their 47th year
8 „ 48th „
6 „ 49th „
9 „ 50th „
1 „ 52d „
1 „ 53d „
1 „ 54th „
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com