Preface

Modern Java

Sometimes it’s hard to believe that a language with literally 20 years of backward compatibility could change so drastically. Prior to the release of Java SE 8 in March of 2014,1 for all of its success as the definitive server-side programming language, Java had acquired the reputation of being “the COBOL of the 21st century.” It was stable, pervasive, and solidly focused on performance. Changes came slowly when they came at all, and companies felt little urgency to upgrade when new versions became available.

That all changed when Java SE 8 was released. Java SE 8 included “Project Lambda,” the major innovation that introduced functional programming concepts into what was arguably the world’s leading object-oriented language. Lambda expressions, method references, and streams fundamentally changed the idioms of the language, and developers have been trying to catch up ever since.

The attitude of this book is not to judge whether the changes are good or bad or could have been done differently. The goal here is to say, “this is what we have, and this is how you use it to get your job done.” That’s why this book is designed as a recipes book. It’s all about what you need to do, and how the new features in Java help you do it.

That said, there are a lot of advantages to the new programming model, once you get used to them. Functional code tends to be simpler and easier to both write and understand. The functional approach favors immutability, which makes writing concurrent code cleaner and more likely to be successful. Back when Java was created, you could still rely on Moore’s law to double your processor speed roughly every 18 months. These days performance improvements come from the fact that even most phones have multiple processors.

Since Java has always been sensitive to backward compatibility, many companies and developers have moved to Java SE 8 without adopting the new idioms. The platform is more powerful even so, and is worth using, not to mention the fact that Oracle formally declared Java 7 end-of-life in April 2015.

It has taken a couple of years, but most Java developers are now working with the Java 8 JDK, and it’s time to dig in and understand what that means and what consequences it has for your future development. This book is designed to make that process easier.

Who Should Read This Book

The recipes in this book assume that the typical reader already is comfortable with Java versions prior to Java SE 8. You don’t need to be an expert, and some older concepts are reviewed, but the book is not intended to be a beginner’s guide to Java or object-oriented programming. If you have used Java on a project before and you are familiar with the standard library, you’ll be fine.

This book covers almost all of Java SE 8, and includes one chapter focused on the new changes coming in Java 9. If you need to understand how the new functional idioms added to the language will change the way you write code, this book is a use-case-driven way of accomplishing that goal.

Java is pervasive on the server side, with a rich support system of open source libraries and tools. The Spring Framework and Hibernate are two of the most popular open source frameworks, and both either require Java 8 as a minimum or will very soon. If you plan to operate in this ecosystem, this book is for you.

How This Book Is Organized

This book is organized into recipes, but it’s difficult to discuss recipes containing lambda expressions, method references, and streams individually without referring to the others. In fact, the first six chapters discuss related concepts, though you don’t have to read them in any particular order.

The chapters are organized as follows:

  • Chapter 1, The Basics, covers the basics of lambda expressions and method references, and follows with the new features of interfaces: default methods and static methods. It also defines the term “functional interface” and explains how it is key to understanding lambda expressions.

  • Chapter 2, The java.util.function Package, presents the new java.util.function package, which was added to the language in Java 8. The interfaces in that package fall into four special categories (consumers, suppliers, predicates, and functions) that are used throughout the rest of the standard library.

  • Chapter 3, Streams, adds in the concept of streams, and how they represent an abstraction that allows you to transform and filter data rather than process it iteratively. The concepts of “map,” “filter,” and “reduce” relate to streams, as shown in the recipes in this chapter. They ultimately lead to the ideas of parallelism and concurrency covered in Chapter 9.

  • Chapter 4, Comparators and Collectors, involves the sorting of streaming data, and converting it back into collections. Partitioning and grouping is also part of this chapter, which turns what are normally considered database operations into easy library calls.

  • Chapter 5, Issues with Streams, Lambdas, and Method References, is a miscellaneous chapter; the idea being that now that you know how to use lambdas, method references, and streams, you can look at ways they can be combined to solve interesting problems. The concepts of laziness, deferred execution, and closure composition are also covered, as is the annoying topic of exception handling.

  • Chapter 6, The Optional Type, discusses one of the more controversial additions to the language—the Optional type. Recipes in this chapter describe how the new type is intended to be used and how you can both create instances and extract values from them. This chapter also revisits the functional idea of map and flat-map operations on Optionals, and how they differ from the same operations on streams.

  • Chapter 7, File I/O, switches to the practical topic of input/output streams (as opposed to functional streams), and the additions made to the standard library to incorporate the new functional concepts when dealing with files and directories.

  • Chapter 8, The java.time Package, shows the basics of the new Date-Time API, and how (at long last) they replace the legacy Date and Calendar classes. The new API is based on the Joda-Time library, which is backed by many developer-years of experience and use and has been rewritten to form the java.time package. Frankly, if this had been the only addition to Java 8, it would have been worth the upgrade.

  • Chapter 9, Parallelism and Concurrency, addresses one of the implicit promises of the stream model: that you can change a sequential stream to a parallel one with a single method call, and thereby take advantage of all the processors available on your machine. Concurrency is a big topic, but this chapter presents the additions to the Java library that make it easy to experiment with and assess when the costs and benefits are worth the effort.

  • Chapter 10, Java 9 Additions, covers many of the changes coming in Java 9, which is currently scheduled to be released September 21, 2017. The details of Jigsaw can fill an entire book by themselves, but the basics are clear and are described in this chapter. Other recipes cover private methods in interfaces, the new methods added to streams, collectors, and Optional, and how to create a stream of dates.2

  • Appendix A, Generics and Java 8, is about the generics capabilities in Java. While generics as a technology was added back in 1.5, most developers only learned the minimum they needed to know to make them work. One glance at the Javadocs for Java 8 and 9 shows that those days are over. The goal of the appendix is to show you how to read and interpret the API so you understand the much more complex method signatures involved.

The chapters, and indeed the recipes themselves, do not have to be read in any particular order. They do complement each other and each recipe ends with references to others, but you can start reading anywhere. The chapter groupings are provided as a way to put similar recipes together, but it is expected that you will jump from one to another to solve whatever problem you may have at the moment.

Conventions Used in This Book

The following typographical conventions are used in this book:

Italic

Indicates new terms, URLs, email addresses, filenames, and file extensions.

Constant width

Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords.

Constant width bold

Shows commands or other text that should be typed literally by the user.

Constant width italic

Shows text that should be replaced with user-supplied values or by values determined by context.

Tip

This element signifies a tip or suggestion.

Note

This element signifies a general note.

Warning

This element indicates a warning or caution.

Using Code Examples

The source code for the book is located in three GitHub repositories: one for the Java 8 recipes (everything but Chapter 10) at https://github.com/kousen/java_8_recipes, one for the Java 9 recipes at https://github.com/kousen/java_9_recipes, and a special one for the larger CompletableFuture example in Recipe 9.7 at https://github.com/kousen/cfboxscores. All are configured as Gradle projects with tests and a build file.

This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Modern Java Recipes by Ken Kousen (O’Reilly). Copyright 2017 Ken Kousen, 978-0-491-97317-2.”

If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at .

O’Reilly Safari

Note

Safari (formerly Safari Books Online) is a membership-based training and reference platform for enterprise, government, educators, and individuals.

Members have access to thousands of books, training videos, Learning Paths, interactive tutorials, and curated playlists from over 250 publishers, including O’Reilly Media, Harvard Business Review, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Adobe, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, and Course Technology, among others.

For more information, please visit http://oreilly.com/safari.

How to Contact Us

Please address comments and questions concerning this book to the publisher:

  • O’Reilly Media, Inc.
  • 1005 Gravenstein Highway North
  • Sebastopol, CA 95472
  • 800-998-9938 (in the United States or Canada)
  • 707-829-0515 (international or local)
  • 707-829-0104 (fax)

To comment or ask technical questions about this book, send email to .

For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com.

Find us on Facebook: http://facebook.com/oreilly

Follow us on Twitter: http://twitter.com/oreillymedia

Watch us on YouTube: http://www.youtube.com/oreillymedia

Acknowledgments

This book is the unexpected result of a conversation I had with Jay Zimmerman back in late July 2015. I was (and still am) a member of the No Fluff, Just Stuff conference tour, and that year several Java 8 talks were being given by Venkat Subramaniam. Jay told me that Venkat had decided to scale back his activity in the coming year and Jay was wondering whether I would be willing to do similar talks in the new season starting in early 2016. I had been coding in Java since the mid-’90s (I started with Java 1.0.6) and had been planning to learn the new APIs anyway, so I agreed.

I have now been giving presentations on the new functional features of Java for a couple of years. By the Fall of 2016 I had completed my last book,3 and since the idea was to write another recipes book for the same publisher I foolishly thought the project would be easy.

Noted science fiction author Neil Gaiman famously once said that after finishing American Gods he thought he knew how to write a novel. His friend corrected him, saying he now knew how to write this novel. I now understand what he meant. The original proposal for this book anticipated about 25 to 30 recipes spanning about 150 pages. The final result you hold in your hand has more than 70 recipes filling nearly 300 pages, but the larger scope and greater detail has produced a much more valuable book than I intended.

Of course, that’s because I had lots of help. The aforementioned Venkat Subramaniam has been extremely helpful, both through his talks, his other books, and private discussions. He also was kind enough to be a technical reviewer on this book, so any remaining errors are all his fault. (No, they’re mine, but please don’t tell him I admitted that.)

I also am very grateful to have had the frequent assistance of Tim Yates, who is one of the best coders I’ve ever met. I knew him from his work in the Groovy community, but his versatility goes well beyond that, as his Stack Overflow rating will show. Rod Hilton, who I met while giving Java 8 presentations on the NFJS tour, was also kind enough to offer a review. Both of their recommendations have been invaluable.

I have been fortunate enough to work with the excellent editors and staff at O’Reilly Media over the course of two books, over a dozen video courses, and many online training classes delivered on their Safari online platform. Brian Foster has been a constant source of support, not to mention his almost magical ability to cut through bureaucracy. I met him while writing my previous book, and though he wasn’t the editor of this one, his help and friendship have been very valuable to me throughout the process.

My editor, Jeff Bleiel, was very understanding as the book doubled in length, and provided the structure and organization needed to keep making progress. I’m very glad we got to work together and hope we will continue to do so in the future.

I need to acknowledge many of my fellow speakers on the NFJS tour, including Nate Schutta, Michael Carducci, Matt Stine, Brian Sletten, Mark Richards, Pratik Patel, Neal Ford, Craig Walls, Raju Gandhi, Kirk Knoernschild, Dan “the Man” Hinojosa, and Janelle Klein for their constant perspective and encouragement. Both writing books and teaching training classes (my actual day job) are solitary pursuits. It’s great having a community of friends and colleagues that I can rely on for perspective, advice, and various forms of entertainment.

Finally, I need to express all my love to my wife Ginger and my son Xander. Without the support and kindness of my family I would not be the person I am today, a fact that grows more obvious to me with each passing year. I can never express what you both mean to me.

1 Yes, it’s actually been over three years since the first release of Java SE 8. I can’t believe it either.

2 Yes, I too wish that the Java 9 chapter had been Chapter 9, but it didn’t seem right to reorder the chapters just for that accidental symmetry. This footnote will have to suffice.

3 Gradle Recipes for Android, also from O’Reilly Media, all about the Gradle build tool as it is applied to Android projects.

Get Modern Java Recipes now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.