www.it-ebooks.info Java in Action: Lambdas, streams, and functional-style programming Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft www.it-ebooks.info Copyright For online information and ordering of this and other Manning books, please visit www.manning.com The publisher offers discounts on this book when ordered in quantity For more information, please contact Special Sales Department Manning Publications Co 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2015 by Manning Publications Co All rights reserved No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine Development editor: Susan Conant Manning Publications Co Technical development editor Al Scherer 20 Baldwin Road Copyeditor: Linda Recktenwald PO Box 761 Proofreader: Katie Tennant Shelter Island, NY 11964 Typesetter: Dennis Dalinnik Cover designer: Maria Tudor www.it-ebooks.info ISBN: 9781617291999 Printed in the United States of America 10 – EBM – 19 18 17 16 15 14 www.it-ebooks.info Dedication To our parents www.it-ebooks.info Table of Contents Copyright Dedication Part Fundamentals 11 Chapter Java 8: why should you care? 12 1.1 Why is Java still changing? 14 1.2 Functions in Java 21 1.3 Streams 28 1.4 Default methods 32 1.5 Other good ideas from functional programming 34 1.6 Summary .36 Chapter Passing code with behavior parameterization 37 2.1 Coping with changing requirements .38 2.2 Behavior parameterization .41 2.3 Tackling verbosity 47 2.4 Real-world examples 52 2.5 Summary 54 Chapter Lambda expressions 56 3.1 Lambdas in a nutshell 57 3.2 Where and how to use lambdas 60 3.3 Putting lambdas into practice: the execute around pattern 66 3.4 Using functional interfaces 70 3.5 Type checking, type inference, and restrictions 76 3.6 Method references 82 3.7 Putting lambdas and method references into practice! .89 3.8 Useful methods to compose lambda expressions 91 3.9 Similar ideas from mathematics 95 3.10 Summary 98 Part Functional-style data processing 99 www.it-ebooks.info Chapter Introducing streams 100 4.1 What are streams? 100 4.2 Getting started with streams 105 4.3 Streams vs collections 108 4.4 Stream operations 113 4.5 Summary 117 Chapter Working with streams 118 5.1 Filtering and slicing 119 5.2 Mapping 123 5.3 Finding and matching .129 5.4 Reducing 132 5.5 Putting it all into practice .140 5.6 Numeric streams 145 5.7 Building streams 152 5.8 Summary 158 Chapter Collecting data with streams 159 6.1 Collectors in a nutshell 160 6.2 Reducing and summarizing 163 6.3 Grouping 172 6.4 Partitioning 180 6.5 The Collector interface 186 6.6 Developing your own collector for better performance .194 6.7 Summary 202 Chapter Parallel data processing and performance .203 7.1 Parallel streams 204 7.2 The fork/join framework 214 7.3 Spliterator 222 7.4 Summary 232 Part Effective Java programming 233 Chapter Refactoring, testing, and debugging 234 8.1 Refactoring for improved readability and flexibility 234 www.it-ebooks.info 8.2 Refactoring object-oriented design patterns with lambdas 242 8.3 Testing lambdas 253 8.4 Debugging 256 8.5 Summary 261 Chapter Default methods 262 9.1 Evolving APIs 265 9.2 Default methods in a nutshell .269 9.3 Usage patterns for default methods 272 9.4 Resolution rules .277 9.5 Summary 284 Chapter 10 Using Optional as a better alternative to null 285 10.1 How you model the absence of a value? 286 10.2 Introducing the Optional class 290 10.3 Patterns for adopting Optional 292 10.4 Practical examples of using Optional 303 10.5 Summary 307 Chapter 11 CompletableFuture: composable asynchronous programming 309 11.1 Futures 311 11.2 Implementing an asynchronous API 314 11.3 Make your code non-blocking 320 11.4 Pipelining asynchronous tasks 328 11.5 Reacting to a CompletableFuture completion 338 11.6 Summary 342 Chapter 12 New Date and Time API 343 12.1 LocalDate, LocalTime, Instant, Duration, and Period 344 12.2 Manipulating, parsing, and formatting dates 350 12.3 Working with different time zones and calendars 358 12.4 Summary 361 Part Beyond Java 363 Chapter 13 Thinking functionally 364 13.1 Implementing and maintaining systems 364 www.it-ebooks.info 13.2 What’s functional programming? .368 13.3 Recursion vs iteration 375 13.4 Summary 379 Chapter 14 Functional programming techniques 381 14.1 Functions everywhere 381 14.2 Persistent data structures 385 14.3 Lazy evaluation with streams 392 14.4 Pattern matching 401 14.5 Miscellany 407 14.6 Summary 410 Chapter 15 Blending OOP and FP: comparing Java and Scala 412 15.1 Introduction to Scala 413 15.2 Functions 422 15.3 Classes and traits 427 15.4 Summary 429 Chapter 16 Conclusions and where next for Java 431 16.1 Review of Java features 431 16.2 What’s ahead for Java? 435 16.3 The final word 446 Appendix A Miscellaneous language updates .447 A.1 Annotations 447 A.2 Generalized target-type inference 450 Appendix B Miscellaneous library updates 452 B.1 Collections 452 B.2 Concurrency 455 B.3 Arrays 458 B.4 Number and Math 459 B.5 Files 460 B.6 Reflection 460 B.7 String 460 Appendix C Performing multiple operations in parallel on a stream 462 www.it-ebooks.info C.1 Forking a stream 462 C.2 Performance considerations 472 Appendix D Lambdas and JVM bytecode 473 D.1 Anonymous classes 473 D.2 Bytecode generation .473 D.3 InvokeDynamic to the rescue 475 D.4 Code-generation strategies 477 Index 479 10 www.it-ebooks.info creating collections immutable vs mutable collections manipulating collections option stream tuples Date class DateFormat class DateTimeException DateTimeFormatter class, 2nd DateTimeFormatterBuilder class DateTimeParseException Daylight Saving Time See DST dayOfWeekInMonth method declaration-site variance declarative declarative programming decrementExact method default modifier defensive checking @Deprecated annotation destructive updates vs functional diamond operator ( ) diamond problem DISTINCT characteristic distinct method, 2nd, 3rd divideUnsigned method don’t repeat yourself See DRY principle DoubleAccumulator class DoubleAdder class DoubleBinaryOperator interface DoubleConsumer interface DoublePredicate interface DoubleStream interface DoubleSupplier interface DoubleUnaryOperator interface 483 www.it-ebooks.info DRY (don’t repeat yourself) principle DST (Daylight Saving Time) Duration class E empty method empty optional objects emptyList method encounter order erasure model error handling estimateSize method, 2nd event handling EventHandler class Exception parameter Executable class execute around pattern behavior parameterization and executing behavior improving code flexibility overview passing lambda expressions using functional interface ExecutionException Executor interface ExecutorService interface, 2nd external iteration, 2nd extracting data F factory design pattern Fibonacci series Files class, 2nd files, building streams from filter method, 2nd, 3rd, 4th, 5th, 6th filtering streams 484 www.it-ebooks.info with predicate skipping elements truncating stream unique elements find method findAny method, 2nd findFirst method, 2nd finish method finisher method first-class functions, 2nd firstDayOfMonth method firstDayOfNextMonth method firstDayOfNextYear method firstDayOfYear method firstInMonth method flatMap method, 2nd, 6th dereferencing chain using optionals finding car insurance company name example overview flattening streams floorDiv method floorMod method for loop forEach method, 2nd, 3rd, 4th forEachRemaining method fork method, 2nd forking step ForkingStreamConsumer class ForkJoinPool class, 2nd format method format package free variables from method, 2nd function composition function descriptors, 2nd, 3rd, 4th Function interface, 2nd @FunctionalInterface annotation 485 www.it-ebooks.info G generate method generic polymorphism generics, 2nd get method, 2nd, 3rd, 4th, 5th getAndAccumulate method getAndUpdate method getAnnotationsByType method getOperationResult method getOrDefault method getResults method getRuntime method getters and setters in Scala Groovy, 2nd, 3rd grouping data, 2nd groupingBy method, 2nd, 3rd Guava library H hashcodes HashSet class Haskell, 2nd higher-order functions, 2nd HijrahDate class I identity function IDENTITY_FINISH collection, 2nd IDEs (integrated development environments) ifPresent method, 2nd, 3rd immutability, 2nd IMMUTABLE characteristic, 2nd immutable collections imperative programming imperative-style Scala 486 www.it-ebooks.info implicit data dependences incrementExact method inference of generic arguments infinite stream Instant class IntBinaryOperator interface IntConsumer interface integrated development environments See IDEs IntelliJ intermediate operations, 2nd internal iteration characteristics of streams external iteration vs IntFunction interface IntPredicate interface IntStream interface IntSupplier interface IntToDoubleFunction interface IntToLongFunction interface IntUnaryOperator interface intValueExact method invoke method invokedynamic instruction, 2nd isDone method Islamic calendar isNegative method ISO_LOCAL_DATE constant isPresent method, 2nd isPrime method isZero method iterate method, 2nd iteration vs recursion J JapaneseDate class Java Concurrency in Practice 487 www.it-ebooks.info Java virtual machine See JVM java.util.concurrent.ForkJoinPool.common.parallelism property JavaFX JDK Enhancement Proposal join method, 2nd, 3rd joining method, 2nd, 3rd joining strings using collectors K keySet method L lambdaj library lastDayOfMonth method lastDayOfNextMonth method lastDayOfNextYear method lastDayOfYear method lastInMonth method late-binding Spliterator lazy evaluation self-defining stream using lazy list limit method, 2nd, 3rd, 4th, 5th lines method LinkedList class list method local variables in lambda expressions LocalDate class LocalDateTime class LocalTime class logicalAnd method logicalOr method logicalXor method LongAccumulator class 488 www.it-ebooks.info LongAdder class LongBinaryOperator interface LongConsumer interface LongFunction interface LongPredicate interface LongStream interface LongSupplier interface LongToDoubleFunction interface LongToIntFunction interface LongUnaryOperator interface longValueExact method M Map interface map method, 2nd, 3rd, 4th, 5th, 6th, 7th mapping streams applying function to each element arrays flatMap method numeric mappingCount method map-reduce mapToDouble method mapToInt method mapToLong method Math class mathematical function mathematics and lambda expressions max method, 2nd maxBy method, 2nd Maybe type memoization, 2nd merge method method minBy method, 2nd MinguoDate class minus method, 2nd 489 www.it-ebooks.info multicore processors, 2nd multilevel matching multipliedBy method multiplyExact method multithreading streams and Streams API and N Nashorn naturalOrder method NavigableMap class NavigableSet class negate method negated method negateExact method NetBeans next method nextDown method nextOrSame method NIO API non-blocking code defined making asynchronous requests overview scaling and using custom Executor using parallel stream noneMatch method, 2nd @NonNull annotation NONNULL characteristic non-strict evaluation now method NullPointerException nullsFirst method nullsLast method 490 www.it-ebooks.info Number class NumberFormatException O ObjDoubleConsumer interface object-oriented programming See OOP ObjIntConsumer interface ObjLongConsumer interface observer design pattern of method, 2nd, 3rd, 4th ofEpochSecond method OffsetDateTime class ofLocale method ofNullable method, 2nd ofPattern method OOP (object-oriented programming), 2nd See also Scala option type, Scala optional methods OptionalDouble class, 2nd OptionalInt class, 2nd OptionalLong class, 2nd or method ORDERED characteristic, 2nd orElse method, 2nd, 3rd orElseGet method, 2nd orElseThrow method, 2nd P parallel method parallelization, 2nd, 3rd, 4th parallelPrefix method parallelSetAll method parallelSort method parallelStream method, 2nd 491 www.it-ebooks.info Parameter class parse method, 2nd parseUnsignedInt method partial functions partially applied function, 2nd partitioning function partitioningBy method, 2nd, 3rd passing code to methods See behavior parameterization performance custom collectors parallel streams Period class plus method, 2nd polymorphism Predicate interface previous method previousOrSame method primitive optionals programming language ecosystem purity putIfAbsent method Pythagorean triples example filtering good combinations generating a values generating b values generating tuples Pythagorean triples explained representing triple running code solution R randomDelay method rangeClosed method, 2nd ranges, streams of readability, improving for code 492 www.it-ebooks.info recursion vs iteration RecursiveTask class reduce method, 2nd, 3rd, 4th reducing method, 2nd refactoring from anonymous classes to lambda expressions from imperative data processing to streams improving code flexibility conditional deferred execution execute around pattern using functional interfaces improving readability from lambda expressions to method references object-oriented design patterns with lambdas chain of responsibility design pattern factory design pattern observer design pattern overview strategy design pattern template method design pattern referential transparency, 2nd reflection registering actions reified generics remainderUnsigned method remove method removeIf method repeated annotations replace method replaceAll method, 2nd Results interface reverse method reversed method reverseOrder method Runnable interface RuntimeException 493 www.it-ebooks.info S safe navigation operator Scala, 2nd, 3rd classes in creating getters and setters data structures creating collections immutable vs mutable collections manipulating collections option stream tuples functional-style functions in anonymous functions closures currying first-class functions imperative-style pattern matching in traits scaling Serializable interface setAll method shared mutable data short-circuiting, 2nd shortValueExact method side effects, 2nd, 3rd, 4th singleton pattern SIZED characteristic, 2nd skip method, 2nd sort method, 2nd SORTED characteristic sorted method, 2nd sorting with Comparator source compatibility 494 www.it-ebooks.info split method spliterator method stack trace defined lambdas and stateful operations stateless lambda expressions stateless operations static methods inside interfaces stdin/stdout strategy design pattern Stream interface groups of operations intermediate operations terminal operations stream method, 2nd StreamForker structural pattern matching SUBSIZED characteristic, 2nd substreams subtractExact method subtractFrom method sum method summarization using collectors summarizingInt method summingDouble method summingInt method, 2nd summingLong method Supplier interface supplier method supplyAsync method synchronized keyword synchronous methods, converting to asynchronous syntactic metadata 495 www.it-ebooks.info T tail-call optimization target type, 2nd target-type inference template method design pattern Temporal interface TemporalAdjusters TemporalField, 2nd terminal operations, 2nd, 3rd @Test annotation ThaiBuddhistDate class thenCombine method thenComparing method, 2nd thenComparingDouble method thenComparingInt method thenComparingLong method thenCompose method thread pools threads TimeoutException toCollection method ToDoubleBiFunction interface ToDoubleFunction interface ToIntBiFunction interface toIntExact method ToIntFunction interface toList method, 2nd ToLongBiFunction interface ToLongFunction interface toSet method, 2nd toUnsignedInt method toUnsignedLong method toUnsignedString method traits in Scala TreeSet class troubleshooting parallel streams truncating streams 496 www.it-ebooks.info tryAdvance method trySplit method, 2nd tuples, Scala type annotations type checking type inference, 2nd, 3rd U UnaryOperator interface unbounded unboxing unit testing lambda expressions unmodifiable collections UnsupportedTemporalType-Exception unwrapping optionals updateAndGet method V value types values, streams from variables in lambda expressions visitor design pattern, 2nd void return W walk method while loop with method withAttribute method work stealing technique 497 www.it-ebooks.info ... operate by reading data from standard input (stdin in Unix and C, System .in in Java) , operating on it, and then writing their results to standard output (stdout in Unix and C, System.out in Java) First,... more in demand We now introduce the new concepts in Java 8, one by one—pointing out on the way the chapters that cover these concepts in more detail 1.2 Functions in Java The word function in programming... are used, so in using Java you’re protecting your way of life as a Java programmer On top of that, we have a feeling you’ll love using Java 8 s new features Ask anyone who’s used Java whether