PDF Functional Interfaces in Java: Fundamentals and Examples 1st Edition Ralph Lecessi [Lecessi download
PDF Functional Interfaces in Java: Fundamentals and Examples 1st Edition Ralph Lecessi [Lecessi download
com
https://textbookfull.com/product/functional-interfaces-in-
java-fundamentals-and-examples-1st-edition-ralph-lecessi-
lecessi/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/microservices-patterns-with-examples-
in-java-1st-edition-chris-richardson/
textboxfull.com
https://textbookfull.com/product/microservices-patterns-with-examples-
in-java-1st-edition-chris-richardson-2/
textboxfull.com
https://textbookfull.com/product/fundamentals-of-information-
systems-9th-edition-ralph-stair/
textboxfull.com
Learning Java Functional Programming 1st Edition Reese
Richard M
https://textbookfull.com/product/learning-java-functional-
programming-1st-edition-reese-richard-m/
textboxfull.com
https://textbookfull.com/product/electrical-phenomena-at-interfaces-
second-edition-fundamentals-measurements-and-applications-ohshima/
textboxfull.com
https://textbookfull.com/product/modern-java-in-action-lambdas-
streams-functional-and-reactive-programming-raoul-gabriel-urma/
textboxfull.com
https://textbookfull.com/product/design-and-analysis-of-connections-
in-steel-structures-fundamentals-and-examples-alfredo-boracchini/
textboxfull.com
https://textbookfull.com/product/cost-accounting-fundamentals-
essential-concepts-and-examples-steven-m-bragg/
textboxfull.com
Functional
Interfaces
in Java
Fundamentals and Examples
—
Ralph Lecessi
Functional Interfaces
in Java
Fundamentals and Examples
Ralph Lecessi
Functional Interfaces in Java: Fundamentals and Examples
Ralph Lecessi
Kendall Park, NJ, USA
iii
Table of Contents
Chapter 3: Predicates��������������������������������������������������������������������������������������������� 45
Section 3.1: The java.util.function Package�������������������������������������������������������������������������������� 45
Section 3.2: The Predicate Interface������������������������������������������������������������������������������������������� 45
Section 3.3: Passing a Predicate to a Method����������������������������������������������������������������������������� 47
Section 3.4: Chains of Functional Interfaces������������������������������������������������������������������������������� 50
Section 3.5: Predicate Chaining Creates Complex Logical Expressions������������������������������������� 50
Section 3.5.1: Chains Involving the OR Operation����������������������������������������������������������������� 50
Section 3.5.2: Chains Involving the AND Operation��������������������������������������������������������������� 52
Section 3.5.3: Chains Involving the ! Operation��������������������������������������������������������������������� 53
Section 3.5.4: Using Predicate.isEqual���������������������������������������������������������������������������������� 54
Section 3.5.5: Using Predicate.not [JAVA 11]������������������������������������������������������������������������ 55
Section 3.6: Overriding Predicate Default Methods�������������������������������������������������������������������� 56
Section 3.7: Specializations of Predicates���������������������������������������������������������������������������������� 57
Section 3.8: Binary Predicates���������������������������������������������������������������������������������������������������� 59
PROJECT 3: Discount Dave���������������������������������������������������������������������������������������������������������� 59
Problem Statement���������������������������������������������������������������������������������������������������������������� 59
Solution��������������������������������������������������������������������������������������������������������������������������������� 60
Short Problems��������������������������������������������������������������������������������������������������������������������������� 67
Long Problems���������������������������������������������������������������������������������������������������������������������������� 67
Chapter 4: Functions���������������������������������������������������������������������������������������������� 69
Section 4.1: The Function Interface�������������������������������������������������������������������������������������������� 69
Section 4.2: Passing a Generic Function to a Method����������������������������������������������������������������� 70
Section 4.2.1: Passing a Function with Restricted or Known Type Parameters�������������������� 71
iv
Table of Contents
Chapter 5: Operators���������������������������������������������������������������������������������������������� 95
Section 5.1: The UnaryOperator Interface����������������������������������������������������������������������������������� 95
Section 5.2: Specializations of UnaryOperator���������������������������������������������������������������������������� 96
Section 5.2.1: Chains Involving UnaryOperator Specializations�������������������������������������������� 97
Section 5.3: The BinaryOperator Interface���������������������������������������������������������������������������������� 98
Section 5.4: Non-generic Specializations of BinaryOperator����������������������������������������������������� 99
PROJECT 5: Calculator�������������������������������������������������������������������������������������������������������������� 100
Problem Statement�������������������������������������������������������������������������������������������������������������� 100
Solution������������������������������������������������������������������������������������������������������������������������������� 100
Short Problems������������������������������������������������������������������������������������������������������������������������� 106
Long Problems�������������������������������������������������������������������������������������������������������������������������� 107
v
Table of Contents
Section 6.3: Using Consumers with println as the Terminal Operation������������������������������������� 112
Section 6.4: Non-generic Specializations of Consumers���������������������������������������������������������� 112
Section 6.5: The BiConsumer Interface������������������������������������������������������������������������������������� 114
Section 6.6: Specializations of BiConsumer������������������������������������������������������������������������������ 115
PROJECT 6: Bank Transactions������������������������������������������������������������������������������������������������� 116
Problem Statement�������������������������������������������������������������������������������������������������������������� 116
Solution������������������������������������������������������������������������������������������������������������������������������� 117
Short Problems������������������������������������������������������������������������������������������������������������������������� 128
Long Problems�������������������������������������������������������������������������������������������������������������������������� 129
vi
Table of Contents
vii
Table of Contents
viii
Table of Contents
ix
Table of Contents
x
Table of Contents
Index��������������������������������������������������������������������������������������������������������������������� 405
xi
About the Author
Ralph Lecessi is a software engineer with over 30 years’
professional programming experience in the aerospace,
telecommunications, and payment industries at companies
including Lockheed Martin, Alcatel-Lucent, AT&T, and
Northrop Grumman. He is currently lead embedded
software developer at TranSendIT, Inc in Mount Laurel,
New Jersey.
Ralph is also the author of JAVATM - The Beginnings—a
text on basic Java programming that includes many examples and diagrams.
Ralph is an adjunct professor of programming at Middlesex County College, where
he teaches basic and object-oriented programming in Java. He lives in South Brunswick,
New Jersey, with his wife and two children.
xiii
About the Technical Reviewer
Manuel Jordan Elera is an autodidactic developer and
researcher who enjoys learning new technologies for his
own experiments and creating new integrations. Manuel
won the 2010 Springy Award Community Champion and
Spring Champion 2013. In his little free time, he reads
the Bible and composes music on his guitar. Manuel is
known as dr_pompeii. He has tech-reviewed numerous
books for Apress, including Pro Spring, Fourth Edition
(2014); Practical Spring LDAP (2013); Pro JPA 2, Second
Edition (2013); and Pro Spring Security (2013). Read his
13 detailed tutorials about many Spring technologies, contact him through his blog at
www.manueljordanelera.blogspot.com, and follow him on his Twitter account,
@dr_pompeii.
xv
Foreword
Functional Interfaces in Java shows how to organize and simplify Java programs through
the use of functional interfaces.
Chapters 1 and 2 introduce functional interfaces and discuss their implementation
using lambda expressions.
Chapters 3 through 7 discuss the functional interfaces present in the java.util.
function package.
Chapters 8 through 15 show how to use functional interfaces to perform various
programming tasks.
The appendix discusses method references and how they can be used in the
implementation of functional interfaces.
The text presents each topic with detailed descriptions and many examples. Each
chapter also contains a project through which I will guide you step by step to the
solution. Each chapter also contains short homework problems which reinforce the
subject matter and longer assignments which utilize the current topic to solve a real-
world problem.
Knowledge of basic Java programming is needed to understand the examples in this
text. If you need a primer on basic Java, I recommend JAVATM- The Beginnings.
Here are some notes regarding the programming style used in this book:
All examples have been tested in Java 9, Java 10, and Java 11 unless otherwise noted.
I hope you enjoy reading Functional Interfaces in Java as much as I have enjoyed
writing it.
—Ralph Lecessi
xvii
CHAPTER 1
Functional Interfaces
Section 1.1: Interfaces in Java
In Java, an interface specifies one or more methods. The interface is a contract which
must be honored by all implementing classes. The interface defined in Listing 1-1
specifies methods method1 and method2.
interface I1
{
void method1();
String method2(String x);
}
Any class that implements an interface must provide implementations for all the
methods declared in the interface (or the class must be declared as abstract). Since the
class defined in Listing 1-2 provides implementations for both method1 and method2,
objects of class C1 can be instantiated.
class C1 implements I1
{
@Override
public void method1() {}
@Override
public String method2(String x) { return x; }
}
1
© Ralph Lecessi 2019
R. Lecessi, Functional Interfaces in Java, https://doi.org/10.1007/978-1-4842-4278-0_1
Chapter 1 Functional Interfaces
interface I2
{
String s = "I2";
static void method1()
{
System.out.println(s);
}
2
Chapter 1 Functional Interfaces
class C2 implements I2
{
@Override
public String method2(String x) { return x; }
}
class C3 implements I2 {}
class TestI2
{
public static void main(String[] args)
{
I2.method1();
I2 objC2 = new C2();
I2 objC3 = new C3();
System.out.println(objC2.method2("Hello"));
System.out.println(objC3.method2("World"));
}
}
PROGRAM OUTPUT:
I2
Hello
I2World
In Java 9, interfaces were allowed to have private methods. Private methods are
useful to call from default methods. The program in Listing 1-4 concatenates a random
integer between 0 and 99 to the string “Hello”. Interface I3 contains private method
getNumber which generates the integer. This method is called by default method M1.
import java.util.Random;
interface I3
{
private int getNumber() { return (new Random()).nextInt(100); }
default String M1(String s)
3
Chapter 1 Functional Interfaces
{
return s + getNumber();
}
}
class C4 implements I3
{
}
class TestI3
{
public static void main(String[] args)
{
I3 objC4 = new C4();
System.out.println(objC4.M1("Hello"));
}
}
PROGRAM OUTPUT:
Hello21
In Java 9, interfaces can also have private static methods. Since the static methods of
an interface can be called without creation of an implementing object, these methods
can only be called by public static methods defined in the interface.
Interface I4 in the following program defines public static method getName which
calls private static method getPrefix to add the prefix “Mr. ” or “Ms. ” based on gender.
The getName method can be called from the main method of class TestI4. The getPrefix
method can be called only from inside method getName.
interface I4
{
private static String getPrefix(String p)
{
return p.equals("male")? "Mr. " : "Ms. ";
}
public static String getName(String n, String p)
4
Chapter 1 Functional Interfaces
{
return getPrefix(p) + n;
}
}
class TestI4
{
public static void main(String[] args)
{
System.out.println(I4.getName("Smith", "female"));
System.out.println(I4.getName("Jones", "male"));
}
}
PROGRAM OUTPUT:
Ms. Smith
Mr. Jones
5
Chapter 1 Functional Interfaces
Functional interfaces are ideal for defining a single problem or operation. In Java 8,
the API was enhanced to utilize functional interfaces. Many of the functional interfaces
can contain static and default methods, making them extendable by the user.
6
Chapter 1 Functional Interfaces
The program in Listing 1-9 provides both named class and anonymous class
implementations for functional interface StringProcessor.
PROGRAM OUTPUT:
Hello
HELLO
7
Chapter 1 Functional Interfaces
class Receipt
{
String item;
double price;
double discount;
double tax;
public Receipt(String i, double a, double d, double s)
{
item = i;
price = a;
discount = d;
tax = s;
}
public Receipt(Receipt r)
{
item = r.item;
price = r.price;
discount = r.discount;
tax = r.tax;
}
}
8
Chapter 1 Functional Interfaces
on price, discount, and tax, but allows implementing classes to override the calculation.
The default method calls private method getDiscounterPrice which applies the
discount to the price.
@FunctionalInterface
interface ReceiptPrinter
{
void print(Receipt receipt);
9
Chapter 1 Functional Interfaces
The following ReceiptPrinter implementation is for merchants who are exempt from
tax. It provides its own implementation of the total calculation which does not include tax.
OUTPUT:
Item : shirt
Amount: 20.0
Disc: 0.05
Tax: 0.07
Total: 20.33
Item : shirt
Amount: 20.0
Disc: 0.05
Total: 19.0
10
Chapter 1 Functional Interfaces
@FunctionalInterface
interface StringProcessor
{
String process(String s);
11
Chapter 1 Functional Interfaces
The static methods can be used to verify the case of the processed string.
String s = toLowerCase.process("FUNCTIONALINTERFACES");
System.out.println(s);
System.out.println("Lower case: " + StringProcessor.isLowerCase(s));
System.out.println("Upper case: " + StringProcessor.isUpperCase(s));
String t = toUpperCase.process(s);
System.out.println("\n" + t);
System.out.println("Lower case: " + StringProcessor.isLowerCase(t));
System.out.println("Upper case: " + StringProcessor.isUpperCase(t));
OUTPUT:
functionalinterfaces
Lower case: true
Upper case: false
FUNCTIONALINTERFACES
Lower case: false
Upper case: true
12
Chapter 1 Functional Interfaces
@FunctionalInterface
interface TwoArgsProcessor<X> {
X process(X arg1, X arg2);
}
class TestTwoArgsProcessor {
public static void main(String[] args)
{
TwoArgsProcessor<Integer> multiplyInts
= new TwoArgsProcessor<>() {
@Override
public Integer process(Integer arg1, Integer arg2)
{
return arg1 * arg2;
}
};
13
Chapter 1 Functional Interfaces
TwoArgsProcessor<Double> addDoubles
= new TwoArgsProcessor<>() {
@Override
public Double process(Double arg1, Double arg2)
{
return arg1 + arg2;
}
};
TwoArgsProcessor<String> compareStrings
= new TwoArgsProcessor<>() {
@Override
public String process(String arg1, String arg2)
{
return arg1.compareTo(arg2) > 0? arg1: arg2;
}
};
System.out.println(multiplyInts.process(2,3));
System.out.println(addDoubles.process(4.1,5.2));
System.out.println(compareStrings.process("ace","age"));
}
}
PROGRAM OUTPUT:
6
9.3
age
14
Random documents with unrelated
content Scribd suggests to you:
"Now we send one time machine back to 1868 by means of the
other. Then one of us travels to 2068 from 1868 while another goes
to that allegedly same year 2068 from the present, from 1968. See
what I'm getting at?"
Shaheen slowly nodded his head and then closed one eye.
"If there's free will," Blackburn mumbled, "they won't meet."
"Let's look for exclusion principles," Freylinghuysen commented,
putting the balls of his fingers together and staring at the ceiling.
Rowan, ignored, watched them for a few seconds and sat down
again. After a while he began to wonder how many experiments it
would take before Pendelton found the proof he was looking for.
THE END
*** END OF THE PROJECT GUTENBERG EBOOK THE GREAT
IMPLICATION ***
Updated editions will replace the previous one—the old editions will
be renamed.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the terms
of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.
• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
1.F.4. Except for the limited right of replacement or refund set forth in
paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.
Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
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