Learning Java Functional Programming - Richard M Reese - E-Book

Learning Java Functional Programming E-Book

Richard M. Reese

0,0
44,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Functional programming is an increasingly popular technology that allows you to simplify many tasks that are often cumbersome and awkward using an object-oriented approach. It is important to understand this approach and know how and when to apply it. Functional programming requires a different mindset, but once mastered it can be very rewarding.

This book simplifies the learning process as a problem is described followed by its implementation using an object-oriented approach and then a solution is provided using appropriate functional programming techniques.

Writing succinct and maintainable code is facilitated by many functional programming techniques including lambda expressions and streams. In this book, you will see numerous examples of how these techniques can be applied starting with an introduction to lambda expressions. Next, you will see how they can replace older approaches and be combined to achieve surprisingly elegant solutions to problems.

This is followed by the investigation of related concepts such as the Optional class and monads, which offer an additional approach to handle problems. Design patterns have been instrumental in solving common problems. You will learn how these are enhanced with functional techniques.

To transition from an object-oriented approach to a functional one, it is useful to have IDE support. IDE tools to refactor, debug, and test functional programs are demonstrated through the chapters. The end of the book brings together many of these functional programming techniques to create a more comprehensive application. You will find this book a very useful resource to learn and apply functional programming techniques in Java.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 316

Veröffentlichungsjahr: 2015

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Learning Java Functional Programming
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Getting Started with Functional Programming
Aspects of functional programming
Functions
Function composition
Fluent interfaces
Strict versus non-strict evaluation
Persistent data structures
Recursion
Parallelism
Optional and monads
Java 8's support for functional style programming
Lambda expressions
Default methods
Functional interfaces
Method and constructor references
Collections
Summary
2. Putting the Function in Functional Programming
Lambda expressions usage
Functional programming concepts in Java
High-order functions
Returning a function
First-class functions
The pure function
Support repeated execution
Eliminating dependencies between functions
Supporting lazy evaluation
Referential transparency
Closure in Java
Currying
Lambda expressions revisited
Java 8 type inference
Exception handling in lambda expressions
Functional interfaces revisited
Creating a functional interface
Common functional interfaces
Function-type functional interfaces
Predicate-type functional interfaces
Consumer-type functional interfaces
Supplier-type functional interfaces
Operator-type functional interfaces
Summary
3. Function Composition and Fluent Interfaces
Introduction to function composition
Creating composite functions prior to Java 8
Creating composite functions in Java 8
Using the Function interface for function composition
Using the Functional interface to supplement methods
Passing instances of the Functional interface
Fluent interfaces
Fluent interfaces in Java 8
Method chaining and cascading
Contrasting method cascading and fluent interfaces
Creating and using fluent interfaces
Using fluent interfaces to hide older interfaces/classes
Using fluent interfaces with the Properties class
Extending fluent interfaces
Default methods and functions
Static default methods
Default methods in Java 8
Multiple inheritance in Java 8
Summary
4. Streams and the Evaluation of Expressions
The Stream class and its use
Intermediate and terminal methods
Creating streams
Fixed length streams
Infinite streams
Using the iterate method to create an infinite stream
Using the generate method to create an infinite stream
Using the Stream class methods
Filter methods
Using the filter method
Using the skip method
Sorting streams
Mapping methods
Understanding the mapping operation
Implementing the map-reduce paradigm
Using the flatmap method
Lazy and eager evaluation
Stream and concurrent processing
Understanding non-inference
Understanding stateless operations
Understanding side effects
Understanding the ordering
Summary
5. Recursion Techniques in Java 8
Recursive data structures
Types of recursion
Using direct recursion
Head and tail recursion
Understanding recursion
The Node class
Using head recursion
Using tail recursion
Using the head and tail recursion
Creating a recursive solution based on a formula
Converting an iterative loop to a recursive solution
Merging two lists
Understanding the program stack
Recursive lambda expressions
Common problems found in recursive solutions
Absence of a base case
Using static or instance variables
Using the pre- and post-increment operators
Recursion implementation techniques
Using a wrapper method
Using short circuiting
Tail call optimization
Converting to a tail call
When to use recursion
Recursion and humor
Summary
6. Optional and Monads
Using the Optional class
Creating Optional instances
Using the Optional class to support return values
Handling missing values
Using the orElse method to get a substitute value
Using the orElseGet method to use a function to get a substitute value
Using the orElseThrow method to throw an exception
Filter and transforming values
Using the Optional class's filter method
Using the Optional class's map method
Optional solution to the Customer problem
Disadvantages of the Optional class
Monads
Monads in Java 8
Using the of method as the unit function
Using the flatMap method
Using the map method
Using the Optional class with strings
Using monads with the Part class
A formal discussion of monads
Associativity
Left identity
Right identity
Summary
7. Supporting Design Patterns Using Functional Programming
Implementing the execute-around-method pattern
Object-oriented solution to the execute-around-method pattern
Functional solution to the execute-around-method pattern
Using the execute-around-method pattern with a stream
Implementing the factory pattern
Object-oriented solution to the factory pattern
Functional solution to the factory pattern
Implementing the command pattern
Object-oriented solution to the command pattern
Functional solution to the command pattern
Implementing the strategy pattern
Object-oriented solution to strategy pattern
Functional solution to the strategy pattern
Using the Function interface
Implementing the visitor pattern
Object-orient solution to the visitor pattern
Functional solution to the visitor pattern
Implementing the template pattern
Object-oriented solution to the template pattern
Functional solution to the template pattern
Summary
8. Refactoring, Debugging, and Testing
Refactoring functional code
NetBeans support for refactoring
Converting anonymous inner classes to lambda expressions
Refactoring multiple code instances
Support of other refactoring operations
Eclipse support for refactoring
Converting anonymous inner classes to lambda expressions
Refactoring multiple code instances
Support of other refactoring operations
Debugging lambda expressions
Using the println method to assist debugging
Using the peek method to assist debugging
Debugging lambda expressions using NetBeans
Debugging lambda expressions using Eclipse
Debugging recursive lambda expressions
Debugging parallel streams
Testing functional programs
Testing lambda expressions
Copying the lambda expression
Using a method reference
Reorganizing the test class
Testing exceptions using a fluent style
Summary
9. Bringing It All Together
Functional Zork
Playing the game
The game's architecture
Understanding the GameElements class
Introducing the Item, Direction, and NPC classes
Implementing the FunctionalZork class
Initializing the game
Initializing the commands
Getting a command from the console
Parsing the command
Executing the command
Implementing the Character class
Implementing the pickup method
Implementing the drop method
Implementing the walk method
Implementing the inventory method
Implementing the Location class
Handling items
Handling NPCs
Handling directions
Summary
Epilogue
Index

Learning Java Functional Programming

Learning Java Functional Programming

Copyright © 2015 Packt Publishing

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.

First published: October 2015

Production reference: 1091015

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78355-848-3

www.packtpub.com

Credits

Author

Richard M Reese

Reviewers

Jose Luis Ordiales Coscia

David Greco

Hossein Kazemi

Amar Potghan

Commissioning Editor

Veena Pagare

Acquisition Editor

Vivek Anantharaman

Content Development Editor

Susmita Sabat

Technical Editor

Prajakta Mhatre

Copy Editor

Charlotte Carneiro

Project Coordinator

Judie Jose

Proofreader

Safis Editing

Indexer

Rekha Nair

Graphics

Jason Monteiro

Abhinash Sahu

Production Coordinator

Aparna Bhagat

Cover Work

Aparna Bhagat

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

Jose Luis Ordiales Coscia is a software engineer with much experience in both academia and the private industry. He has a master's degree in computer science, focusing his research on helping developers improve their service-oriented applications.

He has more than 7 years of experience working in backend development with Java and other JVM languages.

David Greco is a software architect with more than 27 years of working experience. He started his career as a researcher in the field of high-performance computing; thereafter, he moved to the business world, where he worked for different enterprise software vendors and helped to create two start-ups. He played different roles, those of a consultant and software architect and even a CTO. He's an enthusiastic explorer of new technologies, and likes to introduce new technologies into enterprises to improve their businesses. Over the past 5 years, he has fallen in love with big data technologies and typed functional programming—Scala and Haskell. When not working or hacking, he likes to practice karate and listen to jazz and classical music.

Hossein Kazemi is an entrepreneur and software engineer based in Amsterdam, the Netherlands. He holds a master's in artificial intelligence with a major in machine learning and minor in Natural Language Processing (NLP) from the University of Amsterdam. He has more than 5 years of hands-on experience in software development and has worked on projects for large-scale machine learning and NLP using Java and Scala.

Amar Potghan is a polyglot functional programming enthusiast. He has vast experience in building scalable distributed systems. Amar is currently working on Haskell and ClojureScript to build a next generation P2P lending platform for a fintech company in Singapore. Before that, he was working as a consultant at ThoughtWorks and as a senior software engineer for a couple of other global software consultancies where he worked on continuous delivery, microservices, big data, and analytics product development projects. Amar's current interests are functional programming, distributed systems, and machine learning.

www.PacktPub.com

Support files, eBooks, discount offers, and more

For support files and downloads related to your book, please visit www.PacktPub.com.

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 <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

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 PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

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.

The goal of this book is to introduce functional programming techniques to developers who are not familiar with this technology. You will be guided through the use of functional programming techniques with the help of numerous examples. Older imperative and object-oriented approaches will be illustrated and contrasted with equivalent functional programming solutions.

What this book covers

Chapter 1, Getting Started with Functional Programming, introduces the essential elements of functional programming as supported by Java 8. This includes the introduction of functional terms complemented by Java 8 examples.

Chapter 2, Putting the Function in Functional Programming, covers the types of functions found in functional programming languages such as high-order functions, first-class functions, and pure functions. The use of lambda expressions in support of functions is explained.

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.

Chapter 5, Recursion Techniques in Java 8, demonstrates recursion, a very useful functional programming technique. While not new to Java, we explore the topic in depth and examine the use of recursive lambda expressions.

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 7, Supporting Design Patterns Using Functional Programming, illustrates design patterns. They play an important role in Java programming. The impact of the functional style of programming and lambda expressions is illustrated.

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.

Chapter 9, Bringing It All Together, summarizes many of the functional programming techniques presented earlier that are used in the creation of a demonstration application. Such an application provides a concise illustration of how these techniques support the development of robust and maintainable software.

What you need for this book

Java SDK 1.8 is needed for the functional programming examples encountered in the book. Some of the examples use NetBeans 8.02 and Eclipse IDE for Java developers, Mars Release Version 4.5.0.

Who this book is for

This book is for developers who are already proficient in Java and want to learn how to use the functional programming features of Java 8. Familiarity with basic Java object-oriented programming concepts is all that is needed. You will learn how to apply lambda expressions and other functional programming techniques to create a more elegant and maintainable code.

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.

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."

A block of code is shown as follows:

list.forEach(new Consumer<String>() { @Override public void accept(String t) { System.out.println(t); } });

The output of code sequences is formatted as shown here:

Starting FPS GameGenerating FPS ImageRendering FPS ImageUpdating FPS Game

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."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

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.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

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.

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.

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

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.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

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.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.