The code refers to the following articles:
- English: Java Streams (with Examples)
- German: Java Streams (mit Beispielen)
and, in the package eu.happycoders.lambdas, to the articles
and, in the package eu.happycoders.functionalinterfaces, to the articles
- English: Java Functional Interfaces (with Examples)
- German: Funktionale Interfaces in Java (mit Beispielen)
and, in the package eu.happycoders.reduce, to the articles
and, in the package eu.happycoders.tomap, to the article
All examples work on the same data model: the records Book and Author, the enum Genre, and the Library class with eleven public-domain classics.
Every class with a main() method is one chapter of the article and prints the outputs shown there. Run one with java -cp target/classes eu.happycoders.streams.<ClassName> after mvn compile:
Ch1Intro– the same task as a loop and as a stream; the anatomy of a stream pipelineCh2Lambdas– lambda expressions, method references, functional interfacesCh3Sources– creating streams from collections, arrays, ranges, files, and generatorsCh4Intermediate–filter(),map(),flatMap(),mapMulti(),distinct(),sorted(),limit(),skip(),takeWhile(),dropWhile(),peek(),gather()Ch5Terminal–forEach(),collect()and collectors,toList(),toArray(),reduce(),count(),min(),max(),findFirst(),anyMatch(), and the othersCh6Lazy– lazy evaluation: element-by-element processing, short-circuiting, stateful operations, single useCh7Parallel– parallel streamsCh8Mistakes– common mistakes and how to avoid them
The lambda article has its own chapters in eu.happycoders.lambdas, on the same data model (run them with java -cp target/classes eu.happycoders.lambdas.<ClassName>):
Ch1AnonymousVsLambda– the same comparator as an anonymous class and as a lambdaCh2Syntax– parameters, expression and block body, explicit types,var, the unnamed parameter_Ch3TargetType– the four contexts of a target type, functional interfaces, overloaded methodsCh4VariableAccess– effectively final, the one-element-array workaround,this(withScopeandBookFilter)Ch5MethodReferences– the four kinds of method references,this::andsuper::, an ambiguous referenceCh6WhereUsed– lambdas inComparator, collections, maps,Optional, and threadsCh7UnderTheHood– the generated class, identity of capturing and non-capturing lambdas (withLambdaDemoforjavap)Ch8Mistakes– a lambda that is too long, recursion, a lambda in a stack trace (withLambdaTrace)
The functional-interfaces article has its chapters in eu.happycoders.functionalinterfaces (run them with java -cp target/classes eu.happycoders.functionalinterfaces.<ClassName> from the repository root - two chapters read files relative to it):
Ch1Definition–Runnableas the simplest case;Comparatorimplemented by a named class (YearComparator) and by a lambda; the abstract method called directly; default methodsCh2Annotation–@FunctionalInterfaceonTitleFormatter, the error for a second abstract method, an interface without the annotationCh3CoreFour–Function,Predicate,Consumer,SupplierwithandThen(),compose(),identity(),and(),or(),negate(),not(),isEqual(),orElseGet(),toCollection()Ch4Operators–UnaryOperatorinList.replaceAll(),BinaryOperatorinreduce(),maxBy(),Map.merge()Ch5TwoParameters–BiFunction,BiConsumer,BiPredicateinMap.forEach(),computeIfPresent(),replaceAll(),Files.find()Ch6Primitives–ToIntFunction,IntPredicate,IntUnaryOperator,IntFunction,IntBinaryOperator,IntSupplier,ObjIntConsumeron anIntStream; boxingCh7Wildcards–Predicate<? super T>andFunction<? super T, ? extends R>, and a method of our own with and without the wildcardCh8OutsidePackage–Runnable,Callable,Comparator,FileFilter,DirectoryStream.Filter,TemporalAdjusterCh9Custom–TitleFormattervs.Function(nominal typing),ThrowingFunctionfor checked exceptionsCh10Mistakes–Function<T, Boolean>instead ofPredicate,Function<T, Void>instead ofConsumer,UnaryOperator<Integer>instead ofIntUnaryOperator
The reduce() article has its chapters in eu.happycoders.reduce (run them with java -cp target/classes eu.happycoders.reduce.<ClassName>):
Ch1HowItWorks– the sum of 1 to 5 withreduce()and as a loop; every call of the accumulatorCh2Variants– the three variants ofreduce()on full and empty streams, and the two ofIntStreamCh3Applications– product, minimum withBinaryOperator.minBy(), aBigDecimalsum (withPrices) and a sum of the recordMoney,DoubleStream.sum()againstreduce(), predicates and functions chained withreduce(), andand(),andThen()andallMatch()as the more readable alternativesCh4Parallel– accumulator and combiner calls in a parallel stream; a non-neutral identity, a non-associative accumulator, and the accumulator used as combiner, each with its fixCh5ReduceVsCollect– anArrayListas identity,collect()andtoList(), string concatenation againstjoining(),Collectors.reducing()as downstream collectorCh6Fold–Gatherers.fold()in a parallel streamCh7Mistakes–get()on an emptyOptional,mapToInt()instead of boxing, overflow withMath::multiplyExact,BigInteger
The toMap() article has its chapters in eu.happycoders.tomap (run them with java -cp target/classes eu.happycoders.tomap.<ClassName>):
Ch1HowItWorks– title to year withtoMap()and as a loop;Function.identity()for a lookup mapCh2Variants– the three variants oftoMap(): a duplicate key, the merge function,TreeMap::new; a throwing merge function againstcollectingAndThen()Ch3Merging– counting withInteger::sum, concatenating titles (andgroupingBy()withjoining()), the oldest book withBinaryOperator.minBy()Ch4MapType– the order of theHashMap,LinkedHashMapin stream order,EnumMapper genreCh5Null– theNullPointerExceptionfor anullvalue with two and three arguments,filter()andcollect()with three arguments as ways out, anullkey in aTreeMapCh6Unmodifiable–toUnmodifiableMap():UnsupportedOperationException, merge function,nullkeyCh7Applications– filtering, transforming and inverting a map; two lists to one mapCh8VsGroupingBy– lists and counts withtoMap()andgroupingBy(), nested maps withtoMap()as downstream collectorCh9Parallel– the later number wins:toMap()againsttoConcurrentMap()in a parallel streamCh10Mistakes– a merge function that returnsnull, and counting first as the fix; swallowed duplicates
The code requires Java 25 or newer.
Stay up-to-date with the latest Java features with this free PDF Cheat Sheet!
- Avoid lengthy research with this concise overview of all Java versions from Java 10 to Java 27.
- Discover the innovative features of each new Java version, summarized on a single page.
- Impress your team with your up-to-date knowledge of the latest Java version.
👉 Download the free Java Versions PDF
(Hier geht's zur deutschen Version → Java-Versionen PDF)
With this free 1-page PDF cheat sheet, you'll always have the 7 most important complexity classes at a glance.
- Always choose the most efficient data structures and thus increase the performance of your applications.
- Be prepared for technical interviews and confidently present your algorithm knowledge.
- Become a sought-after problem solver and be known for systematically tackling complex problems.
👉 Download the free Big O Cheat Sheet
(Hier geht's zur deutschen Version → O-Notation Cheat Sheet)
👉 Want to stay on top of modern Java? Sign up for the HappyCoders newsletter – Modern Java: new versions & features, performance, and JVM insights – once a month.
(Hier geht's zur deutschen Version → HappyCoders-Newsletter deutsch)
🇩🇪 An alle Java-Entwickler:innen, die durch fundierte Kenntnisse über Datenstrukturen besseren Code schreiben wollen
Trage dich jetzt unverbindlich auf die Warteliste von „Mastering Data Structures in Java“ ein, und erhalte das beste Angebot!


