This document outlines an agenda and provides details for a masterclass on lambda programming in Java. The agenda includes introductions and setup, lambdas and method references, comparators, default methods, and streams I and II. It provides background on the introduction of lambdas in Java 8 and examples of writing lambdas and using method references. It also summarizes new default methods added to interfaces like Comparator and Map in Java 8 for working with lambdas, and indicates labs will be provided to demonstrate and practice these concepts.
JDT Embraces Lambda Expressions - EclipseCon North America 2014Noopur Gupta
Java 8 is coming. It is happening right here. Developers of your favorite Java IDE are participating in shaping this long awaited milestone for the Java ecosystem: On time with the GA of Java 8, JDT will ship its first release with support for developing in Java 8.
If you have a basic understanding of the new features in Java 8, come here and learn how the JDT team mastered the challenges of lifting the Eclipse Java IDE to the next language version.
The main focus of this talk will be on lambda expressions, touching also some changes in the libraries that leverage lambda expressions. We will expose some examples demonstrating the complexity of the language and mention some caveats which should help you avoid some unpleasent surprises.
We will demo how to get started using Java 8 in Eclipse and show the latest tool features for working with lambda expressions including new quick assists etc.
Finally, we'll give a retrospective discussion of the situation of the JDT team, in terms of team changes, contributors, deadlines, interaction with expert groups, with the Eclipse community, and more.
More information about the meetup this presentation was created for can be found at https://www.meetup.com/life-michael/events/255429951/ More information about our Python course (in Hebrew) can be found at http://python.course.lifemichael.com More information about our other courses and services can be found at http://www.lifemichael.com.
JDT Embraces Lambda Expressions - EclipseCon North America 2014Noopur Gupta
Java 8 is coming. It is happening right here. Developers of your favorite Java IDE are participating in shaping this long awaited milestone for the Java ecosystem: On time with the GA of Java 8, JDT will ship its first release with support for developing in Java 8.
If you have a basic understanding of the new features in Java 8, come here and learn how the JDT team mastered the challenges of lifting the Eclipse Java IDE to the next language version.
The main focus of this talk will be on lambda expressions, touching also some changes in the libraries that leverage lambda expressions. We will expose some examples demonstrating the complexity of the language and mention some caveats which should help you avoid some unpleasent surprises.
We will demo how to get started using Java 8 in Eclipse and show the latest tool features for working with lambda expressions including new quick assists etc.
Finally, we'll give a retrospective discussion of the situation of the JDT team, in terms of team changes, contributors, deadlines, interaction with expert groups, with the Eclipse community, and more.
More information about the meetup this presentation was created for can be found at https://www.meetup.com/life-michael/events/255429951/ More information about our Python course (in Hebrew) can be found at http://python.course.lifemichael.com More information about our other courses and services can be found at http://www.lifemichael.com.
Slides from my JAX London 2016 talk, discussing how the new features affect library design. Follows on from the Java SE 8 Best Practices talk - http://www.slideshare.net/scolebourne/java-se-8-best-practices-53975908
Java 8 is coming soon. In this presentation I have outlined the major Java 8 features. You get information about interface improvements, functional interfaces, method references, lambdas, java.util.function, java.util.stream
Cover Basic concept for Functional Programming in Java. Define new functional interfaces, lambda expressions, how to translate lambda expression, JVM deal with new byte code etc. This is not the perfect slides for functional programming, but trying cover simple basic functional programming.
Generics On The JVM (What you don't know will hurt you)Garth Gilmour
Talk delivered to the London Kotlin Users Group. Covering how generics is implemented on the JVM and the different approaches taken by Java and Kotlin to co/contra variance and the lack of reified types.
My presentation slides in KMS TechCon 2014, an internal technology event at KMS Technology Vietnam company.
"Java 8 is one of the most highly anticipated programming language updates in many years. Let me give you an introduction about its new features: Lambda expressions, Method references, Default Methods, Stream API, new JS Engine, new Date/Time API and more..."
This presentation introduces the main features of Scala, an object oriented and functional programming language. The main focus of the slides is to show how the language implements natively some of the patterns and best practices that are no present in other programming languages, such as Java, C++ and so on.
In detail, the presentation spans these concepts:
- Language's main syntax
- Classes, abstract classes, objects and traits (mixin)
- The Option class
- An introduction to generics
- Implicit classes
- Functions
- Recursion (simple and tail)
- Currying
- Call by value / name
The presentation is took from the Software Engineering course I run in the bachelor-level informatics curriculum at the University of Padova.
Functional Programming With Lambdas and Streams in JDK8IndicThreads
The significant new language feature in Java SE 8 is the introduction of Lambda expressions, a way of defining and using anonymous functions. On its own this provides a great way to simplify situations where we would typically use an inner class today. However, Java SE 8 also introduces a range of new classes in the standard libraries that are designed specifically to take advantage of Lambdas. These are primarily included in two new packages: java.util.stream and java.util.function.
After a brief discussion of the syntax and use of Lambda expressions this session will focus on how to use Streams to greatly simplify the way bulk and aggregate operations are handled in Java. We will look at examples of how a more functional approach can be taken in Java using sources, intermediate operations and terminators. We will also discuss how this can lead to improvements in performance for many operations through the lazy evaluation of Streams and how code can easily be made parallel by changing the way the Stream is created.
Session at the IndicThreads.com Confence held in Pune, India on 27-28 Feb 2015
http://www.indicthreads.com
http://pune15.indicthreads.com
With Java 8 released in March 2014, Oracle Java Technology Ambassador James Weaver discusses many of its new features such as lambda expressions, the stream API, and client-side capabilities with the JavaFX library.
Slides from my JAX London 2016 talk, discussing how the new features affect library design. Follows on from the Java SE 8 Best Practices talk - http://www.slideshare.net/scolebourne/java-se-8-best-practices-53975908
Java 8 is coming soon. In this presentation I have outlined the major Java 8 features. You get information about interface improvements, functional interfaces, method references, lambdas, java.util.function, java.util.stream
Cover Basic concept for Functional Programming in Java. Define new functional interfaces, lambda expressions, how to translate lambda expression, JVM deal with new byte code etc. This is not the perfect slides for functional programming, but trying cover simple basic functional programming.
Generics On The JVM (What you don't know will hurt you)Garth Gilmour
Talk delivered to the London Kotlin Users Group. Covering how generics is implemented on the JVM and the different approaches taken by Java and Kotlin to co/contra variance and the lack of reified types.
My presentation slides in KMS TechCon 2014, an internal technology event at KMS Technology Vietnam company.
"Java 8 is one of the most highly anticipated programming language updates in many years. Let me give you an introduction about its new features: Lambda expressions, Method references, Default Methods, Stream API, new JS Engine, new Date/Time API and more..."
This presentation introduces the main features of Scala, an object oriented and functional programming language. The main focus of the slides is to show how the language implements natively some of the patterns and best practices that are no present in other programming languages, such as Java, C++ and so on.
In detail, the presentation spans these concepts:
- Language's main syntax
- Classes, abstract classes, objects and traits (mixin)
- The Option class
- An introduction to generics
- Implicit classes
- Functions
- Recursion (simple and tail)
- Currying
- Call by value / name
The presentation is took from the Software Engineering course I run in the bachelor-level informatics curriculum at the University of Padova.
Functional Programming With Lambdas and Streams in JDK8IndicThreads
The significant new language feature in Java SE 8 is the introduction of Lambda expressions, a way of defining and using anonymous functions. On its own this provides a great way to simplify situations where we would typically use an inner class today. However, Java SE 8 also introduces a range of new classes in the standard libraries that are designed specifically to take advantage of Lambdas. These are primarily included in two new packages: java.util.stream and java.util.function.
After a brief discussion of the syntax and use of Lambda expressions this session will focus on how to use Streams to greatly simplify the way bulk and aggregate operations are handled in Java. We will look at examples of how a more functional approach can be taken in Java using sources, intermediate operations and terminators. We will also discuss how this can lead to improvements in performance for many operations through the lazy evaluation of Streams and how code can easily be made parallel by changing the way the Stream is created.
Session at the IndicThreads.com Confence held in Pune, India on 27-28 Feb 2015
http://www.indicthreads.com
http://pune15.indicthreads.com
With Java 8 released in March 2014, Oracle Java Technology Ambassador James Weaver discusses many of its new features such as lambda expressions, the stream API, and client-side capabilities with the JavaFX library.
Presentation of Lambda in Java 8 for the Hanoi Java User Group on Thursday, April 16, 2015
http://www.meetup.com/Hanoi-Java-User-Group/events/220963110/
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Raffi Khatchadourian
Java 8 is one of the largest upgrades to the popular language and framework in over a decade. In this talk, I will first overview several new, key features of Java 8 that can help make programs easier to read, write, and maintain, especially in regards to collections. These features include Lambda Expressions, the Stream API, and enhanced interfaces, many of which help bridge the gap between functional and imperative programming paradigms and allow for succinct concurrency implementations. Next, I will discuss several open issues related to automatically migrating (refactoring) legacy Java software to use such features correctly, efficiently, and as completely as possible. Solving these problems will help developers to maximally understand and adopt these new features thus improving their software.
What really happens when your Java program runs? After the transformation from Java source through bytecode and machine code to microcode, and the various optimizations that take place along the way, the instructions that are actually executed may be very different from what you imagined when you wrote the program. This session shows what a simple program actually looks like when it really hits the hardware.
Complicating Complexity: Performance in a New Machine AgeMaurice Naftalin
It’s no simple matter to explain the performance of even a simple Java program, when instruction execution time is often overshadowed by other costs. Even when network and IO have been taken into account, two programs with similar computational complexity—their big-O characteristics—can differ in cache usage, with big resulting differences in performance.
For the Java programmer, this means that big-O analysis no longer gives enough guidance in choosing a collection implementation for performance-critical code. In this talk we’ll explore optimization of the memory layout and performance of some simple programs via alternative collection implementations and frameworks, and object layout libraries.
Journey's End – Collection and Reduction in the Stream APIMaurice Naftalin
Popular tutorial (81/85 positive ratings) at JavaOne, San Francisco, October 2015. Video of earlier version (JavaOne 2014) is at https://www.youtube.com/watch?v=6tFZelz7Gvg.
Do you want Software for your Business? Visit Deuglo
Deuglo has top Software Developers in India. They are experts in software development and help design and create custom Software solutions.
Deuglo follows seven steps methods for delivering their services to their customers. They called it the Software development life cycle process (SDLC).
Requirement — Collecting the Requirements is the first Phase in the SSLC process.
Feasibility Study — after completing the requirement process they move to the design phase.
Design — in this phase, they start designing the software.
Coding — when designing is completed, the developers start coding for the software.
Testing — in this phase when the coding of the software is done the testing team will start testing.
Installation — after completion of testing, the application opens to the live server and launches!
Maintenance — after completing the software development, customers start using the software.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Atelier - Innover avec l’IA Générative et les graphes de connaissancesNeo4j
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Allez au-delà du battage médiatique autour de l’IA et découvrez des techniques pratiques pour utiliser l’IA de manière responsable à travers les données de votre organisation. Explorez comment utiliser les graphes de connaissances pour augmenter la précision, la transparence et la capacité d’explication dans les systèmes d’IA générative. Vous partirez avec une expérience pratique combinant les relations entre les données et les LLM pour apporter du contexte spécifique à votre domaine et améliorer votre raisonnement.
Amenez votre ordinateur portable et nous vous guiderons sur la mise en place de votre propre pile d’IA générative, en vous fournissant des exemples pratiques et codés pour démarrer en quelques minutes.
Graspan: A Big Data System for Big Code AnalysisAftab Hussain
We built a disk-based parallel graph system, Graspan, that uses a novel edge-pair centric computation model to compute dynamic transitive closures on very large program graphs.
We implement context-sensitive pointer/alias and dataflow analyses on Graspan. An evaluation of these analyses on large codebases such as Linux shows that their Graspan implementations scale to millions of lines of code and are much simpler than their original implementations.
These analyses were used to augment the existing checkers; these augmented checkers found 132 new NULL pointer bugs and 1308 unnecessary NULL tests in Linux 4.4.0-rc5, PostgreSQL 8.3.9, and Apache httpd 2.2.18.
- Accepted in ASPLOS ‘17, Xi’an, China.
- Featured in the tutorial, Systemized Program Analyses: A Big Data Perspective on Static Analysis Scalability, ASPLOS ‘17.
- Invited for presentation at SoCal PLS ‘16.
- Invited for poster presentation at PLDI SRC ‘16.
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Łukasz Chruściel
No one wants their application to drag like a car stuck in the slow lane! Yet it’s all too common to encounter bumpy, pothole-filled solutions that slow the speed of any application. Symfony apps are not an exception.
In this talk, I will take you for a spin around the performance racetrack. We’ll explore common pitfalls - those hidden potholes on your application that can cause unexpected slowdowns. Learn how to spot these performance bumps early, and more importantly, how to navigate around them to keep your application running at top speed.
We will focus in particular on tuning your engine at the application level, making the right adjustments to ensure that your system responds like a well-oiled, high-performance race car.
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Crescat
Crescat is industry-trusted event management software, built by event professionals for event professionals. Founded in 2017, we have three key products tailored for the live event industry.
Crescat Event for concert promoters and event agencies. Crescat Venue for music venues, conference centers, wedding venues, concert halls and more. And Crescat Festival for festivals, conferences and complex events.
With a wide range of popular features such as event scheduling, shift management, volunteer and crew coordination, artist booking and much more, Crescat is designed for customisation and ease-of-use.
Over 125,000 events have been planned in Crescat and with hundreds of customers of all shapes and sizes, from boutique event agencies through to international concert promoters, Crescat is rigged for success. What's more, we highly value feedback from our users and we are constantly improving our software with updates, new features and improvements.
If you plan events, run a venue or produce festivals and you're looking for ways to make your life easier, then we have a solution for you. Try our software for free or schedule a no-obligation demo with one of our product specialists today at crescat.io
Zoom is a comprehensive platform designed to connect individuals and teams efficiently. With its user-friendly interface and powerful features, Zoom has become a go-to solution for virtual communication and collaboration. It offers a range of tools, including virtual meetings, team chat, VoIP phone systems, online whiteboards, and AI companions, to streamline workflows and enhance productivity.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Understanding Nidhi Software Pricing: A Quick Guide 🌟
Choosing the right software is vital for Nidhi companies to streamline operations. Our latest presentation covers Nidhi software pricing, key factors, costs, and negotiation tips.
📊 What You’ll Learn:
Key factors influencing Nidhi software price
Understanding the true cost beyond the initial price
Tips for negotiating the best deal
Affordable and customizable pricing options with Vector Nidhi Software
🔗 Learn more at: www.vectornidhisoftware.com/software-for-nidhi-company/
#NidhiSoftwarePrice #NidhiSoftware #VectorNidhi
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
GraphSummit Paris - The art of the possible with Graph TechnologyNeo4j
Sudhir Hasbe, Chief Product Officer, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Mind IT Systems
Healthcare providers often struggle with the complexities of chronic conditions and remote patient monitoring, as each patient requires personalized care and ongoing monitoring. Off-the-shelf solutions may not meet these diverse needs, leading to inefficiencies and gaps in care. It’s here, custom healthcare software offers a tailored solution, ensuring improved care and effectiveness.
A Sighting of filterA in Typelevel Rite of Passage
Lambda/Streams Hands-On Lab
1. Lambda Masterclass, JavaDay.ro, December 2018
Lambda Programming Laboratory
A Masterclass for Java Developers
JavaDay.ro 2019
Maurice Naftalin
@mauricenaftalin
2. Lambda Masterclass, JavaDay.ro, December 2018
• Intro + Setup
• Lambdas and Method References
• Comparators
• Default Methods
• Streams I
• Streams II
Agenda
10. Lambda Masterclass, JavaDay.ro, December 2018
Open https://github.com/mauricen/LambdaHOLv2/
Select Branch: Java 8 or Java 9
Click "Clone or download"; choose "Download ZIP"
– save to local disk, expand
Setup 1
11. Lambda Masterclass, JavaDay.ro, December 2018
Setup 2
IntelliJ IDEA
Select New | Project from Existing Sources; select the
new directory LambdaHOLv2-Java8/9, click Open,
then Import project from external model, select
Maven; click Next, Next, and Finish
Check that the module SDK (set from File | Project
Structure… | Modules, Dependencies tab) and the
language level (Sources tab) are set correctly.
Labs are in the package exercises.otherides,
under the directory LambdaLab/test. Detailed lab
instructions are in the README.
Eclipse
Select Preferences | Java | Editor | Folding,
ensure Comments checkbox is ticked.
Select File | Import… | Maven | Existing Maven
Projects, click Next, select new directory
LambdaHOL-v2-Java8/9, click Finish
Labs are in the package exercises.eclipse,
under the directory LambdaLab/test. Detailed
lab instructions are in the README.
12. Lambda Masterclass, JavaDay.ro, December 2018
• Intro + Setup
• Lambdas and Method References
• Comparators
• Default Methods
• Streams I
• Streams II
Agenda
14. Lambda Masterclass, JavaDay.ro, December 2018
Lambdas–taking values to a higher order
public interface Collection<E> {
...
boolean removeAll(Collection<?> c);
...
}
instead of supplying values to
specific library methods
15. Lambda Masterclass, JavaDay.ro, December 2018
Lambdas–taking values to a higher order
public interface Collection<E> {
...
boolean removeAll(Collection<?> c);
...
}
public interface Collection<E> {
...
boolean removeIf(Predicate<? super E> p);
...
}
instead of supplying values to
specific library methods
we want to supply behaviour to
general library methods:
16. Lambda Masterclass, JavaDay.ro, December 2018
Lambdas–taking values to a higher order
Predicate is an interface with a single abstract boolean-valued method test.
The method removeIf executes test for each element, and –
public interface Collection<E> {
...
boolean removeAll(Collection<?> c);
...
}
public interface Collection<E> {
...
boolean removeIf(Predicate<? super E> p);
...
}
instead of supplying values to
specific library methods
we want to supply behaviour to
general library methods:
17. Lambda Masterclass, JavaDay.ro, December 2018
Lambdas–taking values to a higher order
Predicate is an interface with a single abstract boolean-valued method test.
The method removeIf executes test for each element, and –
• if test returns true, removeIf removes that element
public interface Collection<E> {
...
boolean removeAll(Collection<?> c);
...
}
public interface Collection<E> {
...
boolean removeIf(Predicate<? super E> p);
...
}
instead of supplying values to
specific library methods
we want to supply behaviour to
general library methods:
18. Lambda Masterclass, JavaDay.ro, December 2018
How can an instance of an interface represent behaviour?
A behaviour is implemented by a single method!
Predicate is an Interface
19. Lambda Masterclass, JavaDay.ro, December 2018
How can an instance of an interface represent behaviour?
A behaviour is implemented by a single method!
Convention: if an interface has a single abstract method, like Predicate:
then when the behaviour of an instance of the interface is wanted, the
behaviour of that single method is used.
public interface java.util.functions.Predicate<T> {
boolean test(T t);
}
Predicate is an Interface
20. Lambda Masterclass, JavaDay.ro, December 2018
How can an instance of an interface represent behaviour?
A behaviour is implemented by a single method!
Convention: if an interface has a single abstract method, like Predicate:
then when the behaviour of an instance of the interface is wanted, the
behaviour of that single method is used.
public interface java.util.functions.Predicate<T> {
boolean test(T t);
}
Functional Interface
Predicate is an Interface
22. Lambda Masterclass, JavaDay.ro, December 2018
How to make an Interface Instance?
The old way was using an anonymous inner class:
// Predicate returns true for odd values of i
new Predicate<Integer>(){
public boolean test(Integer i) {
return i & 1 == 1;
});
23. Lambda Masterclass, JavaDay.ro, December 2018
How to make an Interface Instance?
The old way was using an anonymous inner class:
and we can still supply that as a method argument:
// Predicate returns true for odd values of i
new Predicate<Integer>(){
public boolean test(Integer i) {
return i & 1 == 1;
});
// remove odd values from integerList
integerList.removeIf(new Predicate<Integer>(){
public boolean test(Integer i) {
return i & 1 == 1;
}));
25. Lambda Masterclass, JavaDay.ro, December 2018
// remove odd numbers from integerList
integerList.removeIf(new Predicate<Integer>(){
public boolean test(Integer i) {
return (i & 1) == 1;
}
});
Stripping Out the Boilerplate
26. Lambda Masterclass, JavaDay.ro, December 2018
// remove odd numbers from integerList
integerList.removeIf(new Predicate<Integer>(){
public boolean test(Integer i) {
return (i & 1) == 1;
}
});
Stripping Out the Boilerplate
Why do we have to say we’re supplying a Predicate?
27. Lambda Masterclass, JavaDay.ro, December 2018
Why do we have to say we’re supplying a Predicate?
// remove odd numbers from integerList
integerList.removeIf(new Predicate<Integer>(){
public boolean test(Integer i) {
return (i & 1) == 1;
}
});
Stripping Out the Boilerplate
28. Lambda Masterclass, JavaDay.ro, December 2018
Why do we have to say we’re supplying a Predicate?
// remove odd numbers from integerList
integerList.removeIf(new Predicate<Integer>(){
public boolean test(Integer i) {
return (i & 1) == 1;
}
});
Stripping Out the Boilerplate
Why do we have to say we’re implementing test, the only abstract method?
29. Lambda Masterclass, JavaDay.ro, December 2018
// remove odd numbers from integerList
integerList.removeIf(new Predicate<Integer>(){
public boolean test(Integer i) {
return (i & 1) == 1;
}
});
Stripping Out the Boilerplate
Why do we have to say we’re implementing test, the only abstract method?
Why do we have to say the type parameter is Integer?
Why do we have to say we’re supplying a Predicate?
30. Lambda Masterclass, JavaDay.ro, December 2018
// remove odd numbers from integerList
integerList.removeIf(new Predicate<Integer>(){
public boolean test(Integer i) {
return (i & 1) == 1;
}
});
Stripping Out the Boilerplate
Why do we have to say we’re implementing test, the only abstract method?
Why do we have to say the type parameter is Integer?
Why do we have to say we’re supplying a Predicate?
31. Lambda Masterclass, JavaDay.ro, December 2018
// remove odd numbers from integerList
integerList.removeIf(i (i & 1) == 1)
Stripping Out the Boilerplate
Why do we have to say we’re implementing test, the only abstract method?
Why do we have to say the type parameter is Integer?
Why do we have to say we’re supplying a Predicate?
32. Lambda Masterclass, JavaDay.ro, December 2018
// remove odd numbers from integerList
integerList.removeIf(i (i & 1) == 1)
Stripping Out the Boilerplate
Why do we have to say we’re implementing test, the only abstract method?
Why do we have to say the type parameter is Integer?
Why do we have to say we’re supplying a Predicate?
All we need is one extra syntax element!
33. Lambda Masterclass, JavaDay.ro, December 2018
// remove odd numbers from integerList
integerList.removeIf(i -> (i & 1) == 1)
Stripping Out the Boilerplate
Why do we have to say we’re implementing test, the only abstract method?
Why do we have to say the type parameter is Integer?
All we need is one extra syntax element!
Why do we have to say we’re supplying a Predicate?
34. Lambda Masterclass, JavaDay.ro, December 2018
// remove odd numbers from integerList
integerList.removeIf(i -> (i & 1) == 1)
Stripping Out the Boilerplate
Why do we have to say we’re implementing test, the only abstract method?
Why do we have to say the type parameter is Integer?
All we need is one extra syntax element!
Why do we have to say we’re supplying a Predicate?
// remove odd numbers from integerList
integerList.removeIf(i -> (i & 1) == 1)
37. Lambda Masterclass, JavaDay.ro, December 2018
Rules for Writing Lambdas
() -> 42
a -> a + 1 // single untyped parameter – can omit parentheses
38. Lambda Masterclass, JavaDay.ro, December 2018
Rules for Writing Lambdas
() -> 42
a -> a + 1 // single untyped parameter – can omit parentheses
(a,b) -> a + b // but they are needed for multiple parameters
39. Lambda Masterclass, JavaDay.ro, December 2018
Rules for Writing Lambdas
() -> 42
a -> a + 1 // single untyped parameter – can omit parentheses
(a,b) -> a + b // but they are needed for multiple parameters
(int a, int b) -> a + b;
// type either all parameters, or none
40. Lambda Masterclass, JavaDay.ro, December 2018
Rules for Writing Lambdas
() -> 42
a -> a + 1 // single untyped parameter – can omit parentheses
(a,b) -> a + b // but they are needed for multiple parameters
(int a, int b) -> a + b;
// type either all parameters, or none
() -> { println(42); return 42; }
// lambda body can be a statement
42. Lambda Masterclass, JavaDay.ro, December 2018
Target Typing
Context is needed to define a lambda’s type:
Runnable r = () -> {} // compiles
43. Lambda Masterclass, JavaDay.ro, December 2018
Target Typing
Context is needed to define a lambda’s type:
Runnable r = () -> {} // compiles
Thread t = new Thread(() -> {}) // compiles
44. Lambda Masterclass, JavaDay.ro, December 2018
Target Typing
Context is needed to define a lambda’s type:
Runnable r = () -> {} // compiles
Thread t = new Thread(() -> {}) // compiles
Object o = () -> {} // illegal
45. Lambda Masterclass, JavaDay.ro, December 2018
Method References
Sometimes it’s more convenient to write lambdas as
method references. There are four kinds:
example lambda equivalent
constructor ArrayList::new () -> new ArrayList()
static Integer::max (x,y) -> Integer.max(x,y)
bound “abc"::concat str -> "abc".concat(str)
unbound String::length str -> str.length()
47. Lambda Masterclass, JavaDay.ro, December 2018
• Intro + Setup
• Lambdas and Method References
• Comparators
• Default Methods
• Streams I
• Streams II
Agenda
48. Lambda Masterclass, JavaDay.ro, December 2018
Comparator
Comparators were enhanced with static and default
methods in Java 8. Now, instead of writing this:
Comparator<Person> cmpr = new Comparator<>() {
@Override
public int compare(Person p1, Person p2) {
int cmp = p1.getLastName().compareTo(p2.getLastName());
if (cmp == 0) {
return p1.getFirstName().compareTo(p2.getFirstName());
} else {
return cmp;
}
}
};
49. Lambda Masterclass, JavaDay.ro, December 2018
Comparator
We can instead write
using default and factory methods on Comparator
Comparator<Person> cmp =
Comparator.comparing(Person::getLastName)
.thenComparing(Person::getFirstName)
.thenComparing(Person::getAge);
53. Lambda Masterclass, JavaDay.ro, December 2018
• Intro + Setup
• Lambdas and Method References
• Comparators
• Default Methods
• Streams 1
• Streams II
Agenda
54. Lambda Masterclass, JavaDay.ro, December 2018
Iterable<T>
forEach(Consumer<T> c)
supplies each element in turn to c
removeIf(Predicate<T> p)
removes elements satisfying p
compute(K key, BiFunction<K,V,V> remappingFunction)
computes a new mapping from key and its current mapped value (or null)
computeIfAbsent(K key, Function<K,V> mfn)
if there is no current mapping for key, creates one using mfn and enters it
computeIfPresent(K key, BiFunction<K,V,V> remappingFunction)
creates a mapping from key (if present and non-null) and its current mapped value
forEach(BiConsumer<K,V> c)
executes c for each key-value pair in this Map
merge(K key, V v, BiFunction<V,V,V> remappingFunction)
if key present, calculates new value from old value and v, o.w. associates key with v
putIfAbsent(K key, V value)
associates key with value if key is not present or is null
remove(Object k, Object val)
removes mapping for k from this map if it is present and has the value val
replace(K key, V oldValue, V newValue)
replaces the entry for key only if currently mapped to oldvalue
replaceAll(BiFunction<K,V,V> fn)
replaces each entry’s value with the result of applying fn to the entry’s key and value
replaceAll(UnaryOperator<E> op)
replaces each element with the result of applying op to it
Map<K,V>
List<E>
55. Lambda Masterclass, JavaDay.ro, December 2018
Default Methods on Map
returns name argument(s)
void forEach BiConsumer<K,V>
void replaceAll BiFunction<K,V,V>
V computeIfAbsent K, Function<K,V>
V computeIfPresent K, BiFunction<K,V,V>
V compute K, BiFunction<K,V,V>
V merge K, V, BiFunction<K,V,V>
boolean remove Object, Object
V replace K, V
boolean replace K, V, V
V putIfAbsent K, V
69. name returns interface used FI signature
filter Stream<T> Predicate<T> T ➞ boolean
map Stream<U> Function<T,U> T ➞ U
flatMap Stream<R> Function<T,Stream<R>> T ➞ Stream<R>
peek Stream<T> Consumer<T> T ➞ void
Stateless Intermediate Operations
34
70. name returns interface used FI signature
filter Stream<T> Predicate<T> T ➞ boolean
map Stream<U> Function<T,U> T ➞ U
flatMap Stream<R> Function<T,Stream<R>> T ➞ Stream<R>
peek Stream<T> Consumer<T> T ➞ void
Stateless Intermediate Operations
34
mapToInt IntStream ToIntFunction<T> T ➞ int
mapToLong LongStream ToLongFunction<T> T ➞ long
mapToDouble DoubleStream ToDoubleFunction<T> T ➞ double
88. name returns type used FI signature
limit Stream<T> long
skip Stream<T> long
sorted Stream<T> Comparator<T> (T, T) ➞ int
distinct Stream<T>
takeWhile* Stream<T> Predicate<T>
dropWhile* Stream<T> Predicate<T>
Stateful Intermediate Operations
* added in Java 9
89. Lambda Masterclass, JavaDay.ro, December 2018
Collectors: Journey’s End for a Stream
The Life of a Stream Element
• Born (at a spliterator)
• Transformed (by intermediate operations)
• Collected (by a terminal operation)
90. Lambda Masterclass, JavaDay.ro, December 2018
Collectors: Journey’s End for a Stream
The Life of a Stream Element
• Born (at a spliterator)
• Transformed (by intermediate operations)
• Collected (by a terminal operation)
91. Lambda Masterclass, JavaDay.ro, December 2018
Collectors: Journey’s End for a Stream
The Life of a Stream Element
• Born (at a spliterator)
• Transformed (by intermediate operations)
• Collected (by a terminal operation)
92. Lambda Masterclass, JavaDay.ro, December 2018
Collectors: Journey’s End for a Stream
?
The Life of a Stream Element
• Born (at a spliterator)
• Transformed (by intermediate operations)
• Collected (by a terminal operation)
95. Lambda Masterclass, JavaDay.ro, December 2018
Side-effecting Operations
Side-effecting operations
• forEach, forEachOrdered
people.stream()
.forEach(System.out::println);
• So could we calculate total ages like this?
int sum = 0;
people.stream()
.mapToInt(Person::getAge)
.forEach(a -> { sum += a });
people.stream()
.forEach(System.out::println);
int sum = 0;
people.stream()
.mapToInt(Person::getAge)
.forEach(a -> { sum += a; });
96. Lambda Masterclass, JavaDay.ro, December 2018
Side-effecting Operations
Side-effecting operations
• forEach, forEachOrdered
people.stream()
.forEach(System.out::println);
• So could we calculate total ages like this?
int sum = 0;
people.stream()
.mapToInt(Person::getAge)
.forEach(a -> { sum += a });
people.stream()
.forEach(System.out::println);
int sum = 0;
people.stream()
.mapToInt(Person::getAge)
.forEach(a -> { sum += a; });
Don’t do this!
97. Lambda Masterclass, JavaDay.ro, December 2018
• Using an accumulator:
Reduction – Why?
int[] vals = new int[100];
Arrays.setAll(vals, i -> i);
int sum = 0;
for (int i = 0 ; i < vals.length ; i++) {
sum += vals[i];
}
98. Lambda Masterclass, JavaDay.ro, December 2018
• Using an accumulator:
Reduction – Why?
int[] vals = new int[100];
Arrays.setAll(vals, i -> i);
int sum = 0;
for (int i = 0 ; i < vals.length ; i++) {
sum += vals[i];
}
0 1 2 3
+
+
+
101. Lambda Masterclass, JavaDay.ro, December 2018
• Avoiding an accumulator:
Reduction – Why?
int[] vals = new int[100];
Arrays.setAll(vals, i -> i);
OptionalInt sum = Arrays.stream(vals)
.reduce((a,b) -> a + b);
+ +
+
1 2 30
102. Lambda Masterclass, JavaDay.ro, December 2018
• Avoiding an accumulator:
Reduction – Why?
int[] vals = new int[100];
Arrays.setAll(vals, i -> i);
OptionalInt sum = Arrays.stream(vals)
.reduce((a,b) -> a + b);
+ +
+
1 2 30
+
+
+
103. Lambda Masterclass, JavaDay.ro, December 2018
• Avoiding an accumulator:
Reduction – Why?
int[] vals = new int[100];
Arrays.setAll(vals, i -> i);
OptionalInt sum = Arrays.stream(vals)
.reduce((a,b) -> a + b);
BinaryOperator must be associative!
+ +
+
1 2 30
+
+
+
104. Lambda Masterclass, JavaDay.ro, December 2018
• Avoiding an accumulator:
Reduction – Why?
int[] vals = new int[100];
Arrays.setAll(vals, i -> i);
OptionalInt sum = Arrays.stream(vals)
.reduce((a,b) -> a + b);
BinaryOperator must be associative!
a + (b + c) = (a + b) + c
+ +
+
1 2 30
+
+
+
108. Lambda Masterclass, JavaDay.ro, December 2018
Reduction on ImmutableValues
Reduction works on immutable values too
BigDecimal[] vals = new BigDecimal[100];
Arrays.setAll(vals, i -> new BigDecimal(i));
Optional<BigDecimal> sum = Arrays.stream(vals)
.reduce(BigDecimal::add);
113. Lambda Masterclass, JavaDay.ro, December 2018
What about Collections?
This also works with immutable values.
And even collections – sort of … but then
• for each element, client code has to create a new empty
collection and add the single element to it,
• and combine collections using addAll
114. Lambda Masterclass, JavaDay.ro, December 2018
What about Collections?
This also works with immutable values.
And even collections – sort of … but then
• for each element, client code has to create a new empty
collection and add the single element to it,
• and combine collections using addAll
... it’s hopelessly inefficient!
117. Lambda Masterclass, JavaDay.ro, December 2018
What about Collections?
This also works with immutable values.
But collections need to
118. Lambda Masterclass, JavaDay.ro, December 2018
What about Collections?
This also works with immutable values.
But collections need to
• be initialised
119. Lambda Masterclass, JavaDay.ro, December 2018
What about Collections?
This also works with immutable values.
But collections need to
• be initialised
• have individual elements added
120. Lambda Masterclass, JavaDay.ro, December 2018
What about Collections?
This also works with immutable values.
But collections need to
• be initialised
• have individual elements added
• be merged
124. Lambda Masterclass, JavaDay.ro, December 2018
Reduction over an Identity
BigDecimal[] vals = new BigDecimal[100];
Arrays.setAll(vals, i -> new BigDecimal(i));
BigDecimal sum = Arrays.stream(vals)
.reduce(BigDecimal.ZERO, BigDecimal::add);
Works for primitives (of course) and also immutable objects:
127. Lambda Masterclass, JavaDay.ro, December 2018
So, Reduction to Collections?
Reduction over an identity doesn’t work with
collections at all
128. Lambda Masterclass, JavaDay.ro, December 2018
So, Reduction to Collections?
Reduction over an identity doesn’t work with
collections at all
• reduction reuses the identity element
129. Lambda Masterclass, JavaDay.ro, December 2018
So, Reduction to Collections?
Reduction over an identity doesn’t work with
collections at all
• reduction reuses the identity element
We need something better!
131. Lambda Masterclass, JavaDay.ro, December 2018
The Answer – Collectors
a
a
a
e0 e1 e2 e3
a
a
a
() -> []
e4 e5 e6 e7
aa
c
() -> []
132. Lambda Masterclass, JavaDay.ro, December 2018
The Answer – Collectors
a
a
a
e0 e1 e2 e3
a
a
a
() -> []
e4 e5 e6 e7
aa
c
a: accumulator
c: combiner
() -> []
134. Lambda Masterclass, JavaDay.ro, December 2018
So to define a collector, you need to provide
• Supplier
• Accumulator
• Combiner
Collectors
135. Lambda Masterclass, JavaDay.ro, December 2018
So to define a collector, you need to provide
• Supplier
• Accumulator
• Combiner
That sounds really hard…
Collectors
136. Lambda Masterclass, JavaDay.ro, December 2018
So to define a collector, you need to provide
• Supplier
• Accumulator
• Combiner
That sounds really hard…
Good then that we don’t have to do it!
Collectors
137. Lambda Masterclass, JavaDay.ro, December 2018
Example Domain
city: City
name: String
age: int
Person
Person amy = new Person(Athens, "Amy", 21);
...
List<Person> people = Arrays.asList(jon, amy, bill);
138. Lambda Masterclass, JavaDay.ro, December 2018
• Why collectors?
• Using the predefined collectors
• Worked problems
Journey’s End – Agenda
139. Lambda Masterclass, JavaDay.ro, December 2018
Using the Predefined Collectors
Predefined Standalone Collectors – from factory
methods in Collectors class
• toList(), toSet(), toMap(), joining()
• toMap(), toCollection()
• groupingBy(), partitioningBy(),
groupingByConcurrent()
140. Lambda Masterclass, JavaDay.ro, December 2018
Using the Predefined Collectors
Predefined Standalone Collectors – from factory
methods in Collectors class
• toList(), toSet(), toMap(), joining()
• toMap(), toCollection()
• groupingBy(), partitioningBy(),
groupingByConcurrent()
framework provides
the Supplier
141. Lambda Masterclass, JavaDay.ro, December 2018
Using the Predefined Collectors
Predefined Standalone Collectors – from factory
methods in Collectors class
• toList(), toSet(), toMap(), joining()
• toMap(), toCollection()
• groupingBy(), partitioningBy(),
groupingByConcurrent()
user provides
the Supplier
framework provides
the Supplier
142. Lambda Masterclass, JavaDay.ro, December 2018
Using the Predefined Collectors
Predefined Standalone Collectors – from factory
methods in Collectors class
• toList(), toSet(), toMap(), joining()
• toMap(), toCollection()
• groupingBy(), partitioningBy(),
groupingByConcurrent()
user provides
the Supplier
produce a
classification map
framework provides
the Supplier
159. Lambda Masterclass, JavaDay.ro, December 2018
toMap(Function<T,K> keyMapper,
Function<T,U> valueMapper)
Stream<Person>
toMap() Map<City,String>
bill
160. Lambda Masterclass, JavaDay.ro, December 2018
toMap(Function<T,K> keyMapper,
Function<T,U> valueMapper)
Stream<Person>
toMap() Map<City,String>
bill
Person::getCity
161. Lambda Masterclass, JavaDay.ro, December 2018
toMap(Function<T,K> keyMapper,
Function<T,U> valueMapper)
Stream<Person>
toMap() Map<City,String>
London
bill
162. Lambda Masterclass, JavaDay.ro, December 2018
toMap(Function<T,K> keyMapper,
Function<T,U> valueMapper)
Stream<Person>
toMap() Map<City,String>
London
bill Person::getName
163. Lambda Masterclass, JavaDay.ro, December 2018
toMap(Function<T,K> keyMapper,
Function<T,U> valueMapper)
Stream<Person>
toMap() Map<City,String>
London “Bill”
bill Person::getName
164. Lambda Masterclass, JavaDay.ro, December 2018
toMap(Function<T,K> keyMapper,
Function<T,U> valueMapper)
Stream<Person>
toMap() Map<City,String>
London “Bill”
165. Lambda Masterclass, JavaDay.ro, December 2018
toMap(Function<T,K> keyMapper,
Function<T,U> valueMapper)
Stream<Person>
toMap() Map<City,String>
amy
London “Bill”
166. Lambda Masterclass, JavaDay.ro, December 2018
toMap(Function<T,K> keyMapper,
Function<T,U> valueMapper)
Stream<Person>
toMap() Map<City,String>
Athens
amy
London “Bill”
167. Lambda Masterclass, JavaDay.ro, December 2018
toMap(Function<T,K> keyMapper,
Function<T,U> valueMapper)
Stream<Person>
toMap() Map<City,String>
“Amy”Athens
London “Bill”
168. Lambda Masterclass, JavaDay.ro, December 2018
toMap(Function<T,K> keyMapper,
Function<T,U> valueMapper)
Stream<Person>
toMap() Map<City,String>
“Amy”Athens
jon
London “Bill”
169. Lambda Masterclass, JavaDay.ro, December 2018
toMap(Function<T,K> keyMapper,
Function<T,U> valueMapper)
Stream<Person>
toMap() Map<City,String>
“Amy”Athens
London “Bill”
Tulsa “Jon”
170. Lambda Masterclass, JavaDay.ro, December 2018
toMap(Function<T,K> keyMapper,
Function<T,U> valueMapper)
toMap() Map<City,String>
“Amy”Athens
London “Bill”
Tulsa “Jon”
171. Lambda Masterclass, JavaDay.ro, December 2018
toMap(Function<T,K> keyMapper,
Function<T,U> valueMapper)
toMap() Map<City,String>
“Amy”Athens
London “Bill”
Tulsa “Jon”
181. Lambda Masterclass, JavaDay.ro, December 2018
Collectors API
Factory methods in the Collectors class.They
produce standalone collectors, accumulating to:
• framework-supplied containers
• custom collections
• classification maps
190. Lambda Masterclass, JavaDay.ro, December 2018
Collectors API
Factory methods in the Collectors class.They
produce standalone collectors, accumulating to:
• framework-supplied containers
• custom collections
• classification maps
191. Lambda Masterclass, JavaDay.ro, December 2018
Collecting to Classification Maps
groupingBy
• simple
• with downstream
• with downstream and map factory
partitioningBy
192. Lambda Masterclass, JavaDay.ro, December 2018
groupingBy(Function<T,K> classifier)
Uses the classifier function to make a classification mapping
Like toMap(), except that the values placed in the map are lists of
the elements, one List corresponding to each classification key:
For example, use Person.getCity() to make a Map<City,List<Person>>
Map<City,List<Person>> peopleByCity = people.stream()
.collect(Collectors.groupingBy(Person::getCity));
193. Lambda Masterclass, JavaDay.ro, December 2018
Stream<Person>
groupingBy() Map<City,List<Person>>
bill
jon
amy Athens
London
Collector<Person,?,Map<City,List<Person>
groupingBy(Function<Person,City>)
Classifier
Person→City
194. Lambda Masterclass, JavaDay.ro, December 2018
Stream<Person>
groupingBy() Map<City,List<Person>>
bill
jon
amy Athens
London
groupingBy(Function<Person,City>)
195. Lambda Masterclass, JavaDay.ro, December 2018
Stream<Person>
groupingBy() Map<City,List<Person>>
bill
jon
amy Athens
bill London
groupingBy(Function<Person,City>)
196. Lambda Masterclass, JavaDay.ro, December 2018
Stream<Person>
groupingBy() Map<City,List<Person>>
bill
jon
amy Athens
billLondon
groupingBy(Function<Person,City>)
[ ]
197. Lambda Masterclass, JavaDay.ro, December 2018
Stream<Person>
groupingBy() Map<City,List<Person>>
bill
jon
amy Athens [ ]
bill
amy
London
groupingBy(Function<Person,City>)
[ ]
198. Lambda Masterclass, JavaDay.ro, December 2018
Stream<Person>
groupingBy() Map<City,List<Person>>
bill
jon
amy Athens [ ]
[ , ]bill
amy
jonLondon
groupingBy(Function<Person,City>)
199. Lambda Masterclass, JavaDay.ro, December 2018
groupingBy() Map<City,List<Person>>
bill
jon
amy Athens [ ]
[ , ]bill
amy
jonLondon
groupingBy(Function<Person,City>)
200. Lambda Masterclass, JavaDay.ro, December 2018
groupingBy() Map<City,List<Person>>
bill
jon
amy
Athens [ ]
[ , ]bill
amy
jonLondon
groupingBy(Function<Person,City>)
201. Lambda Masterclass, JavaDay.ro, December 2018
groupingBy(Function<T,K> classifier)
Uses the classifier function to make a classification mapping
Like toMap(), except that the values placed in the map are lists of
the elements, one List corresponding to each classification key:
For example, use Person.getCity() to make a Map<City,List<Person>>
Map<City,List<Person>> peopleByCity = people.stream()
.collect(Collectors.groupingBy(Person::getCity));
202. Lambda Masterclass, JavaDay.ro, December 2018
groupingBy(classifier, downstream)
Uses the classifier function to make a classification mapping into a
container defined by a downstream Collector
Like toMap(), except that the values placed in the map are containers
of the elements, one container corresponding to each classification key:
For example, use Person.getCity() to make a Map<City,Set<Person>>
Map<City,Set<Person>> peopleByCity = people.stream()
.collect(Collectors.groupingBy(Person::getCity,toSet()));
203. Lambda Masterclass, JavaDay.ro, December 2018
groupingBy(Function classifier,Collector downstream))
Stream<Person>
groupingBy()
Map<City,Set<Person>
bill
jon
amy
London
Athens
Downstream
Collector
—
toSet()
Stream<Person
>
Classifier
Person→City
204. Lambda Masterclass, JavaDay.ro, December 2018
groupingBy(Function classifier,Collector downstream))
Stream<Person>
groupingBy()
Map<City,Set<Person>
bill
jon
amy
London
Athens
205. Lambda Masterclass, JavaDay.ro, December 2018
groupingBy(Function classifier,Collector downstream))
Stream<Person>
groupingBy()
Map<City,Set<Person>
bill
jon
amy
London
Athens
bill
206. Lambda Masterclass, JavaDay.ro, December 2018
groupingBy(Function classifier,Collector downstream))
Stream<Person>
groupingBy()
Map<City,Set<Person>
bill
jon
amy
London
Athens
bill
207. Lambda Masterclass, JavaDay.ro, December 2018
groupingBy(Function classifier,Collector downstream))
Stream<Person>
groupingBy()
Map<City,Set<Person>
bill
jon
amy
London
Athens
bill
208. Lambda Masterclass, JavaDay.ro, December 2018
groupingBy(Function classifier,Collector downstream))
Stream<Person>
groupingBy()
Map<City,Set<Person>
bill
jon
amy
London
Athensamy
bill
209. Lambda Masterclass, JavaDay.ro, December 2018
groupingBy(Function classifier,Collector downstream))
Stream<Person>
groupingBy()
Map<City,Set<Person>
bill
jon
amy
London
Athens amy
bill
210. Lambda Masterclass, JavaDay.ro, December 2018
groupingBy(Function classifier,Collector downstream))
Stream<Person>
groupingBy()
Map<City,Set<Person>
bill
jon
amy
London
Athens amy
bill
211. Lambda Masterclass, JavaDay.ro, December 2018
groupingBy(Function classifier,Collector downstream))
Stream<Person>
groupingBy()
Map<City,Set<Person>
bill
jon
amy
London
Athens amy
jon bill
212. Lambda Masterclass, JavaDay.ro, December 2018
groupingBy(Function classifier,Collector downstream))
Stream<Person>
groupingBy()
Map<City,Set<Person>
bill
jon
amy
London
Athens amy
jon
bill
213. Lambda Masterclass, JavaDay.ro, December 2018
groupingBy(Function classifier,Collector downstream))
groupingBy()
Map<City,Set<Person>
bill
jon
amy
London
Athens amy
jon
bill
214. Lambda Masterclass, JavaDay.ro, December 2018
groupingBy(Function classifier,Collector downstream))
groupingBy()
Map<City,Set<Person>
bill
jon
amy
London
Athens amy
jon
bill
215. Lambda Masterclass, JavaDay.ro, December 2018
groupingBy(Function classifier,Collector downstream))
groupingBy()
Map<City,Set<Person>
bill
jon
amy
London
Athens { }amy
{ , }jonbill
216. Lambda Masterclass, JavaDay.ro, December 2018
groupingBy(Function classifier,Collector downstream))
groupingBy()
Map<City,Set<Person>
bill
jon
amy
London
Athens { }amy
{ , }jonbill
217. Lambda Masterclass, JavaDay.ro, December 2018
mapping(Function mapper,Collector downstream))
Applies a mapping function to each input element before passing it
to the downstream collector.
218. Lambda Masterclass, JavaDay.ro, December 2018
mapping(Function mapper,Collector downstream))
Applies a mapping function to each input element before passing it
to the downstream collector.
Set<City> inhabited = people.stream()
.collect(mapping(Person::getCity,toSet()));
Animation example
219. Journey’s End, JavaOne, September 2016
mapping(Function mapper,Collector downstream))
LondonStream<Person>
mapping()
bill
jon
amy Athens
Mapper
Person→City
Downstream
Collector
—
toSet()
Stream<City>
Set<City>
220. Journey’s End, JavaOne, September 2016
mapping(Function mapper,Collector downstream))
LondonStream<Person>
mapping()
bill
jon
amy Athens
Set<City>
221. Journey’s End, JavaOne, September 2016
mapping(Function mapper,Collector downstream))
LondonStream<Person>
mapping()
bill
jon
amy Athens
London
Set<City>
222. Journey’s End, JavaOne, September 2016
mapping(Function mapper,Collector downstream))
LondonStream<Person>
mapping()
bill
jon
amy Athens
Athens
London
Set<City>
223. Journey’s End, JavaOne, September 2016
mapping(Function mapper,Collector downstream))
LondonStream<Person>
mapping()
bill
jon
amy Athens
Athens
LondonLondon
Set<City>
224. Journey’s End, JavaOne, September 2016
mapping(Function mapper,Collector downstream))
London
mapping()
bill
jon
amy Athens
Athens
LondonLondon
Set<City>
225. Journey’s End, JavaOne, September 2016
mapping(Function mapper,Collector downstream))
London
mapping()
bill
jon
amy
{ ,
}
Athens
Athens
London
Set<City>
226. Journey’s End, JavaOne, September 2016
mapping(Function mapper,Collector downstream))
London
mapping()
bill
jon
amy
{ ,
}
Athens
Athens
London
Set<City>
227. Lambda Masterclass, JavaDay.ro, December 2018
mapping(Function mapper,Collector downstream))
Applies a mapping function to each input element before passing it
to the downstream collector.
Set<City> inhabited = people.stream()
.collect(mapping(Person::getCity,toSet()));
Animation example
228. Lambda Masterclass, JavaDay.ro, December 2018
mapping(Function mapper,Collector downstream))
Applies a mapping function to each input element before passing it
to the downstream collector.
Set<City> inhabited = people.stream()
.collect(mapping(Person::getCity,toSet()));
Map<City,String> namesByCity = people.stream()
.collect(groupingBy(Person::getCity,
mapping(Person::getName,joining()));
Animation example
Sensible example
229. Collectors’ Fair, JavaOne, October 2016
groupingBy()
bill
jon
amy Athens
London
Collector<Person,?,String>
Classifier
Person→City
mapping()
Mapper
Person→String
Stream<String>
joining()
Collector<CharSequence,?,String>
Nesting Collectors