Venkat Subramaniam — «Functional Programming in Java
Total Page:16
File Type:pdf, Size:1020Kb
Praise for Functional Programming in Java Venkat has done a superb job of bringing core functional language concepts to the Java ecosystem. Once you have peered into his looking glass of functional language design, it will be hard to go back to old-school imperative programming. ➤ Stephen Chin, Java technology ambassador and JavaOne content chair The introduction of lambdas to Java 8 has made me excited to use Java again, and Venkat’s combination of technical details and best practices make it easy to apply functional thinking to this new feature. ➤ Kimberly D. Barnes, senior software engineer Java 8 lambda expressions are an incredibly important new language feature. Every Java developer should read this excellent book and learn how to use them effectively. ➤ Chris Richardson, software architect and Java champion Many can explain lambdas; Venkat makes them useful. ➤ Kirk Pepperdine, Java performance tuning expert I highly recommend this book for Java programmers who want to get up to speed with functional programming in Java 8. It is a very concise book but still provides a comprehensive overview of Java 8. ➤ Nilanjan Raychaudhuri, author and developer at Typesafe Functional Programming in Java Harnessing the Power of Java 8 Lambda Expressions Venkat Subramaniam The Pragmatic Bookshelf Dallas, Texas • Raleigh, North Carolina Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade- marks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun. For more information, as well as the latest Pragmatic titles, please visit us at http://pragprog.com. Sir Charles Antony Richard Hoare’s quote is used by permission of the ACM. Abelson and Sussman’s quote is used under Creative Commons license. The team that produced this book includes: Jacquelyn Carter (editor) Potomac Indexing, LLC (indexer) Candace Cunningham (copyeditor) David J Kelly (typesetter) Janet Furlow (producer) Ellie Callahan (support) For international rights, please contact [email protected]. Copyright © 2014 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. ISBN-13: 978-1-937785-46-8 Encoded using the finest acid-free high-entropy binary digits. Book version: P1.0—February 2014 To the loving memory of my grandmothers, Kuppammal and Jayalakshmi. I cherish my wonder years under your care. Contents Foreword . xi Acknowledgments . xiii Preface . xv 1. Hello, Lambda Expressions! . 1 Change the Way You Think 1 The Big Gains of Functional-Style Code 5 Why Code in the Functional Style? 6 Evolution, Not Revolution 12 A Little Sugar to Sweeten 15 Recap 17 2. Using Collections . 19 Iterating through a List 19 Transforming a List 23 Finding Elements 26 Reusing Lambda Expressions 27 Using Lexical Scoping and Closures 29 Picking an Element 33 Reducing a Collection to a Single Value 35 Joining Elements 38 Recap 40 3. Strings, Comparators, and Filters . 41 Iterating a String 41 Implementing the Comparator Interface 44 Multiple and Fluent Comparisons 51 Using the collect Method and the Collectors Class 52 Listing All Files in a Directory 56 Listing Select Files in a Directory 57 Contents • viii Listing Immediate Subdirectories Using flatMap 59 Watching a File Change 60 Recap 62 4. Designing with Lambda Expressions . 63 Separating Concerns Using Lambda Expressions 63 Delegating Using Lambda Expressions 68 Decorating Using Lambda Expressions 72 A Peek into the default Methods 77 Creating Fluent Interfaces Using Lambda Expressions 80 Dealing with Exceptions 83 Recap 86 5. Working with Resources . 87 Cleaning Up Resources 87 Using Lambda Expressions to Clean Up Resources 91 Managing Locks 95 Creating Concise Exception Tests 97 Recap 101 6. Being Lazy . 103 Delayed Initialization 103 Lazy Evaluations 108 Leveraging the Laziness of Streams 111 Creating Infinite, Lazy Collections 115 Recap 119 7. Optimizing Recursions . 121 Using Tail-Call Optimization 121 Speeding Up with Memoization 129 Recap 134 8. Composing with Lambda Expressions . 135 Using Function Composition 135 Using MapReduce 138 Taking a Leap to Parallelize 143 Recap 145 9. Bringing It All Together . 147 Essential Practices to Succeed with the Functional Style 147 Performance Concerns 151 Adopting the Functional Style 153 Contents • ix A1. Starter Set of Functional Interfaces . 155 A2. Syntax Overview . 157 A3. Web Resources . 163 Bibliography . 165 Index . 167 Foreword Venkat Subramaniam would never be described as a “waterfall” sort of guy. So, when he mentioned that he was starting on a Java 8 book—long before the design of Java 8 was settled—I was not at all surprised. It was clear this was going to be an “agile” book project. Despite having to more than occasionally rework the text as the language and library features evolved, Venkat had a secret advantage—he knew where we were going. The Java 8 design was heavily influenced by the core principles of functional programming: functions as values, immutability, and statelessness. We didn’t do this because functional programming is trendy or cool; we did it because programs that are expressed as stateless transformations on immutable data, rather than as modifications of mutable data structures, tend to be easier to read and main- tain, to be less error prone, and to parallelize more gracefully. The new features introduced in Java 8 were designed together to facilitate devel- opment of more expressive and parallel-friendly libraries. Lambda expressions reduce the syntactic overhead of encoding behavior as data; default methods allow existing libraries to evolve over time, enabling core JDK classes such as Collections to take advantage of lambda expressions; the java.util.stream package leverages these language features to offer rich aggregate operations on collections, arrays, and other data sources in a declarative, expressive, and parallel-friendly manner. All of this adds up to more powerful and performant code, as well as a more pleasant programming experience. This book not only provides lots of examples of how to use these new features, but offers readers a peek into the underlying principles behind their design, and why they result in better code. Let Venkat be your guide to this new and improved Java—you’re in for a treat. Brian Goetz Java Language Architect, Oracle Corporation September 2013 report erratum • discuss Acknowledgments Writing a book is like taking a road trip—we know where we’re heading, but some details emerge only after the start. The journey may involve detours— opportunities to explore unexpected places—and it’s more fun with good company. I’m thankful for the great company of people on this voyage: smart reviewers, an amazing editor, a wonderful set of people at The Pragmatic Bookshelf, and a very supportive family. I first thank the Java language team members at Oracle for their hard work to bring the functional style of programming to one of the most popular mainstream languages. You’ve taken the language in the right direction—not through shortcuts and quick fixes, but by way of sound reasoning and prudent design decisions. Kudos, team. I express my sincere gratitude to the smart developers who volunteered their personal time to review this book. Thank you, Kimberly Barnes, Fred Daoud, Raju Gandhi, Marty Hall, Praveen Kumar, Rebecca Parsons, Kirk Pepperdine, Chris Richardson, Ian Roughley, Nate Schutta, Ken Sipe, and Dan Sline. Your comments were critical yet very constructive and motivational; they helped make this book better. I’m honored and humbled by Bruce Tate reviewing this book. He’s been a great mentor for me over the years. He reviewed this book multiple times, at different stages, and took the time to motivate me as to why certain changes were essential. Thank you, Bruce. I’d also like to express my gratitude to Brian Goetz for reviewing the book multiple times, for the encouragement starting early on, and for kindly agreeing to write the foreword. Any errors in the book are solely mine. The biggest benefit of publishing a beta copy of a book is the opportunity to improve it based on valuable feedback from early readers. I’m indebted to the following readers for taking their valuable time to provide feedback on the forum for this book or reporting errors on the errata page. Thank you, Greg Helton, Günter Jantzen, Narayanan Jayaratchagan, Wacek Kusnierczyk, Nabeel Ali Memon, Marc-Daniel Ortega, Arjo Ouwens, Philip Schwarz, report erratum • discuss Acknowledgments • xiv Ekaterina Sh, Dan Talpau, Benjamin Tan, Brian Tarbox, Marco Vermeulen, and Jason Weden. I benefited greatly from every interaction with Jackie Carter. She did not just edit; she motivated me and helped shape this book. Thank you, Jackie, for your hard work, fast responses, and truly making this a fun experience. Impatience is one of my many weaknesses, but the kind folks at The Pragmatic Bookshelf turned that into a strength when I set out to write this book. Susannah Pfalzer, Andy Hunt, Dave Thomas, and several others worked behind the scenes to help me succeed on a self-imposed fast-paced schedule.