SlideShare a Scribd company logo

Lambdas in Java 8

Start programming in a more functional style. This is the first in a two part series on lambdas and streams in Java 8 presented at the JoziJug.

Lambdas in Java 8

1 of 39
Download to read offline
Lambdas in Java 8
Start programming in a more functional style
Background
Who am I?
• Tobias Coetzee
• I’m a Technical Lead at BBD
• I present the Java Expert Level Certifications at BBD (EJB,
JPA, etc.)
• I’m currently a banker
• Part of the JoziJug organising committee
• I like to run
• This presentation is based on a Simon Ritter course
• @tobiascode
• https://github.com/Jozi-JUG/lamdatraining
ASK QUESTIONS, SWAG FOR
EVERYONE!!
Outcomes
What are the take away’s?
• Why should we care about lambdas
• Apply lambdas to everyday problems
• Determine when to apply lambdas (and when not to!)
• How does the lambda syntax work?
• What are functional interfaces?
• Convert anonymous classes to lambda expressions
• Debug lambda expressions
Why Lambdas?
Why lambdas?
Why care about concurrency in Java?
• CPU’s are getting much faster, but we are getting more cores to use.
• We need to parallelise our processing.
• The functional programming paradigm lends itself better to parallel
processing as there is no external state.
Concurrency history in Java
• Java 1 had threads.
• Java 5 had java.util.concurrent (BlockingQueue, Executers, etc.).
• Java 7 had Fork/Join framework.
• Java 8 gives us Lambdas.

Recommended

Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8icarter09
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsEmiel Paasschens
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features OverviewSergii Stets
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New FeaturesNaveen Hegde
 

More Related Content

What's hot

Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8LivePerson
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8Talha Ocakçı
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryPray Desai
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to ScalaRahul Jain
 
Functional programming principles and Java 8
Functional programming principles and Java 8Functional programming principles and Java 8
Functional programming principles and Java 8Dragos Balan
 
Java 8 lambdas expressions
Java 8 lambdas expressionsJava 8 lambdas expressions
Java 8 lambdas expressionsLars Lemos
 
How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01
How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01
How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01Jérôme Rocheteau
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave ImplicitMartin Odersky
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in JavaMudit Gupta
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptRangana Sampath
 
Functional programming for the Advanced Beginner
Functional programming for the Advanced BeginnerFunctional programming for the Advanced Beginner
Functional programming for the Advanced BeginnerLuis Atencio
 
What's new in Java 8
What's new in Java 8What's new in Java 8
What's new in Java 8Kyle Smith
 
Java- Updates in java8-Mazenet solution
Java- Updates in java8-Mazenet solutionJava- Updates in java8-Mazenet solution
Java- Updates in java8-Mazenet solutionMazenetsolution
 

What's hot (20)

Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Functional programming principles and Java 8
Functional programming principles and Java 8Functional programming principles and Java 8
Functional programming principles and Java 8
 
Java SE 8 library design
Java SE 8 library designJava SE 8 library design
Java SE 8 library design
 
Java 8 lambdas expressions
Java 8 lambdas expressionsJava 8 lambdas expressions
Java 8 lambdas expressions
 
Simplicitly
SimplicitlySimplicitly
Simplicitly
 
How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01
How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01
How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in Java
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Functional programming for the Advanced Beginner
Functional programming for the Advanced BeginnerFunctional programming for the Advanced Beginner
Functional programming for the Advanced Beginner
 
Java SE 8
Java SE 8Java SE 8
Java SE 8
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 
What's new in Java 8
What's new in Java 8What's new in Java 8
What's new in Java 8
 
Scala basic
Scala basicScala basic
Scala basic
 
Java- Updates in java8-Mazenet solution
Java- Updates in java8-Mazenet solutionJava- Updates in java8-Mazenet solution
Java- Updates in java8-Mazenet solution
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
 

Similar to Lambdas in Java 8

Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project LambdaRahman USTA
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Nayden Gochev
 
Java 8 New features
Java 8 New featuresJava 8 New features
Java 8 New featuresSon Nguyen
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhHarmeet Singh(Taara)
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsNewCircle Training
 
Functional Interfaces and Method References.pptx
Functional Interfaces and Method References.pptxFunctional Interfaces and Method References.pptx
Functional Interfaces and Method References.pptxMuhammadSalman701062
 
Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Simon Ritter
 
A brief tour of modern Java
A brief tour of modern JavaA brief tour of modern Java
A brief tour of modern JavaSina Madani
 
Functional programming with_jdk8-s_ritter
Functional programming with_jdk8-s_ritterFunctional programming with_jdk8-s_ritter
Functional programming with_jdk8-s_ritterSimon Ritter
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesRaffi Khatchadourian
 
Functional Programming With Lambdas and Streams in JDK8
 Functional Programming With Lambdas and Streams in JDK8 Functional Programming With Lambdas and Streams in JDK8
Functional Programming With Lambdas and Streams in JDK8IndicThreads
 

Similar to Lambdas in Java 8 (20)

Java8
Java8Java8
Java8
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Lambdas
LambdasLambdas
Lambdas
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
 
Java 8 New features
Java 8 New featuresJava 8 New features
Java 8 New features
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singh
 
14274730 (1).ppt
14274730 (1).ppt14274730 (1).ppt
14274730 (1).ppt
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
Functional Interfaces and Method References.pptx
Functional Interfaces and Method References.pptxFunctional Interfaces and Method References.pptx
Functional Interfaces and Method References.pptx
 
Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8
 
A brief tour of modern Java
A brief tour of modern JavaA brief tour of modern Java
A brief tour of modern Java
 
Functional programming with_jdk8-s_ritter
Functional programming with_jdk8-s_ritterFunctional programming with_jdk8-s_ritter
Functional programming with_jdk8-s_ritter
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to Interfaces
 
Functional Programming With Lambdas and Streams in JDK8
 Functional Programming With Lambdas and Streams in JDK8 Functional Programming With Lambdas and Streams in JDK8
Functional Programming With Lambdas and Streams in JDK8
 
2014 java functional
2014 java functional2014 java functional
2014 java functional
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
c++ Unit III - PPT.pptx
 

More from Tobias Coetzee

Serverless - Applications Running in Their Natural State
Serverless - Applications Running in Their Natural StateServerless - Applications Running in Their Natural State
Serverless - Applications Running in Their Natural StateTobias Coetzee
 
Relationship Counselling with Neo4j
Relationship Counselling with Neo4jRelationship Counselling with Neo4j
Relationship Counselling with Neo4jTobias Coetzee
 
Swagger: Restful documentation that won't put you to sleep
Swagger: Restful documentation that won't put you to sleepSwagger: Restful documentation that won't put you to sleep
Swagger: Restful documentation that won't put you to sleepTobias Coetzee
 
Use Neo4j In Your Next Java Project
Use Neo4j In Your Next Java ProjectUse Neo4j In Your Next Java Project
Use Neo4j In Your Next Java ProjectTobias Coetzee
 
How to prepare your Enterprise for NoSQL
How to prepare your Enterprise for NoSQLHow to prepare your Enterprise for NoSQL
How to prepare your Enterprise for NoSQLTobias Coetzee
 

More from Tobias Coetzee (6)

Serverless - Applications Running in Their Natural State
Serverless - Applications Running in Their Natural StateServerless - Applications Running in Their Natural State
Serverless - Applications Running in Their Natural State
 
Relationship Counselling with Neo4j
Relationship Counselling with Neo4jRelationship Counselling with Neo4j
Relationship Counselling with Neo4j
 
Swagger: Restful documentation that won't put you to sleep
Swagger: Restful documentation that won't put you to sleepSwagger: Restful documentation that won't put you to sleep
Swagger: Restful documentation that won't put you to sleep
 
Use Neo4j In Your Next Java Project
Use Neo4j In Your Next Java ProjectUse Neo4j In Your Next Java Project
Use Neo4j In Your Next Java Project
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
How to prepare your Enterprise for NoSQL
How to prepare your Enterprise for NoSQLHow to prepare your Enterprise for NoSQL
How to prepare your Enterprise for NoSQL
 

Recently uploaded

21ST CENTURY LITERACY FROM TRADITIONAL TO MODERN
21ST CENTURY LITERACY FROM TRADITIONAL TO MODERN21ST CENTURY LITERACY FROM TRADITIONAL TO MODERN
21ST CENTURY LITERACY FROM TRADITIONAL TO MODERNRonnelBaroc
 
My sample product research idea for you!
My sample product research idea for you!My sample product research idea for you!
My sample product research idea for you!KivenRaySarsaba
 
Navigating the Never Normal Strategies for Portfolio Leaders
Navigating the Never Normal Strategies for Portfolio LeadersNavigating the Never Normal Strategies for Portfolio Leaders
Navigating the Never Normal Strategies for Portfolio LeadersOnePlan Solutions
 
Q1 Memory Fabric Forum: XConn CXL Switches for AI
Q1 Memory Fabric Forum: XConn CXL Switches for AIQ1 Memory Fabric Forum: XConn CXL Switches for AI
Q1 Memory Fabric Forum: XConn CXL Switches for AIMemory Fabric Forum
 
Tete thermostatique Zigbee MOES BRT-100 V2.pdf
Tete thermostatique Zigbee MOES BRT-100 V2.pdfTete thermostatique Zigbee MOES BRT-100 V2.pdf
Tete thermostatique Zigbee MOES BRT-100 V2.pdfDomotica daVinci
 
5 Things You Shouldn’t Do at Salesforce World Tour Sydney 2024!
5 Things You Shouldn’t Do at Salesforce World Tour Sydney 2024!5 Things You Shouldn’t Do at Salesforce World Tour Sydney 2024!
5 Things You Shouldn’t Do at Salesforce World Tour Sydney 2024!XfilesPro
 
M.Aathiraju Self Intro.docx-AD21001_____
M.Aathiraju Self Intro.docx-AD21001_____M.Aathiraju Self Intro.docx-AD21001_____
M.Aathiraju Self Intro.docx-AD21001_____Aathiraju
 
2) Presentation_Overview_ISO_16140-3_Method_verification_20210322.pptx
2) Presentation_Overview_ISO_16140-3_Method_verification_20210322.pptx2) Presentation_Overview_ISO_16140-3_Method_verification_20210322.pptx
2) Presentation_Overview_ISO_16140-3_Method_verification_20210322.pptxssuser796efb
 
Introduction to Serverless with AWS Lambda in C#.pptx
Introduction to Serverless with AWS Lambda in C#.pptxIntroduction to Serverless with AWS Lambda in C#.pptx
Introduction to Serverless with AWS Lambda in C#.pptxBrandon Minnick, MBA
 
OTel Orientation_ How to Train Teams (OTel in Practice).pdf
OTel Orientation_ How to Train Teams (OTel in Practice).pdfOTel Orientation_ How to Train Teams (OTel in Practice).pdf
OTel Orientation_ How to Train Teams (OTel in Practice).pdfPaige Cruz
 
Manual Eurotronic Thermostatic Valve Comry Z-Wave
Manual Eurotronic Thermostatic Valve Comry Z-WaveManual Eurotronic Thermostatic Valve Comry Z-Wave
Manual Eurotronic Thermostatic Valve Comry Z-WaveDomotica daVinci
 
AUGMENTED REALITY (AR) IN DAILY LIFE: EXPANDING BEYOND GAMING
AUGMENTED REALITY (AR) IN DAILY LIFE: EXPANDING BEYOND GAMINGAUGMENTED REALITY (AR) IN DAILY LIFE: EXPANDING BEYOND GAMING
AUGMENTED REALITY (AR) IN DAILY LIFE: EXPANDING BEYOND GAMINGLiveplex
 
Curtain Module Manual Zigbee Neo CS01-1C.pdf
Curtain Module Manual Zigbee Neo CS01-1C.pdfCurtain Module Manual Zigbee Neo CS01-1C.pdf
Curtain Module Manual Zigbee Neo CS01-1C.pdfDomotica daVinci
 
Artificial-Intelligence-in-Marketing-Data.pdf
Artificial-Intelligence-in-Marketing-Data.pdfArtificial-Intelligence-in-Marketing-Data.pdf
Artificial-Intelligence-in-Marketing-Data.pdfIsidro Navarro
 
Z-Wave Fan coil Thermostat Heltun_HE-HT01_User_Manual.pdf
Z-Wave Fan coil Thermostat Heltun_HE-HT01_User_Manual.pdfZ-Wave Fan coil Thermostat Heltun_HE-HT01_User_Manual.pdf
Z-Wave Fan coil Thermostat Heltun_HE-HT01_User_Manual.pdfDomotica daVinci
 
Avoiding Bad Stats and the Benefits of Playing Trivia with Friends: PancakesC...
Avoiding Bad Stats and the Benefits of Playing Trivia with Friends: PancakesC...Avoiding Bad Stats and the Benefits of Playing Trivia with Friends: PancakesC...
Avoiding Bad Stats and the Benefits of Playing Trivia with Friends: PancakesC...Adrian Sanabria
 
Bit N Build Poland
Bit N Build PolandBit N Build Poland
Bit N Build PolandGDSC PJATK
 
Q1 Memory Fabric Forum: Advantages of Optical CXL​ for Disaggregated Compute ...
Q1 Memory Fabric Forum: Advantages of Optical CXL​ for Disaggregated Compute ...Q1 Memory Fabric Forum: Advantages of Optical CXL​ for Disaggregated Compute ...
Q1 Memory Fabric Forum: Advantages of Optical CXL​ for Disaggregated Compute ...Memory Fabric Forum
 
2024 February Patch Tuesday
2024 February Patch Tuesday2024 February Patch Tuesday
2024 February Patch TuesdayIvanti
 
Q1 Memory Fabric Forum: SMART CXL Product Lineup
Q1 Memory Fabric Forum: SMART CXL Product LineupQ1 Memory Fabric Forum: SMART CXL Product Lineup
Q1 Memory Fabric Forum: SMART CXL Product LineupMemory Fabric Forum
 

Recently uploaded (20)

21ST CENTURY LITERACY FROM TRADITIONAL TO MODERN
21ST CENTURY LITERACY FROM TRADITIONAL TO MODERN21ST CENTURY LITERACY FROM TRADITIONAL TO MODERN
21ST CENTURY LITERACY FROM TRADITIONAL TO MODERN
 
My sample product research idea for you!
My sample product research idea for you!My sample product research idea for you!
My sample product research idea for you!
 
Navigating the Never Normal Strategies for Portfolio Leaders
Navigating the Never Normal Strategies for Portfolio LeadersNavigating the Never Normal Strategies for Portfolio Leaders
Navigating the Never Normal Strategies for Portfolio Leaders
 
Q1 Memory Fabric Forum: XConn CXL Switches for AI
Q1 Memory Fabric Forum: XConn CXL Switches for AIQ1 Memory Fabric Forum: XConn CXL Switches for AI
Q1 Memory Fabric Forum: XConn CXL Switches for AI
 
Tete thermostatique Zigbee MOES BRT-100 V2.pdf
Tete thermostatique Zigbee MOES BRT-100 V2.pdfTete thermostatique Zigbee MOES BRT-100 V2.pdf
Tete thermostatique Zigbee MOES BRT-100 V2.pdf
 
5 Things You Shouldn’t Do at Salesforce World Tour Sydney 2024!
5 Things You Shouldn’t Do at Salesforce World Tour Sydney 2024!5 Things You Shouldn’t Do at Salesforce World Tour Sydney 2024!
5 Things You Shouldn’t Do at Salesforce World Tour Sydney 2024!
 
M.Aathiraju Self Intro.docx-AD21001_____
M.Aathiraju Self Intro.docx-AD21001_____M.Aathiraju Self Intro.docx-AD21001_____
M.Aathiraju Self Intro.docx-AD21001_____
 
2) Presentation_Overview_ISO_16140-3_Method_verification_20210322.pptx
2) Presentation_Overview_ISO_16140-3_Method_verification_20210322.pptx2) Presentation_Overview_ISO_16140-3_Method_verification_20210322.pptx
2) Presentation_Overview_ISO_16140-3_Method_verification_20210322.pptx
 
Introduction to Serverless with AWS Lambda in C#.pptx
Introduction to Serverless with AWS Lambda in C#.pptxIntroduction to Serverless with AWS Lambda in C#.pptx
Introduction to Serverless with AWS Lambda in C#.pptx
 
OTel Orientation_ How to Train Teams (OTel in Practice).pdf
OTel Orientation_ How to Train Teams (OTel in Practice).pdfOTel Orientation_ How to Train Teams (OTel in Practice).pdf
OTel Orientation_ How to Train Teams (OTel in Practice).pdf
 
Manual Eurotronic Thermostatic Valve Comry Z-Wave
Manual Eurotronic Thermostatic Valve Comry Z-WaveManual Eurotronic Thermostatic Valve Comry Z-Wave
Manual Eurotronic Thermostatic Valve Comry Z-Wave
 
AUGMENTED REALITY (AR) IN DAILY LIFE: EXPANDING BEYOND GAMING
AUGMENTED REALITY (AR) IN DAILY LIFE: EXPANDING BEYOND GAMINGAUGMENTED REALITY (AR) IN DAILY LIFE: EXPANDING BEYOND GAMING
AUGMENTED REALITY (AR) IN DAILY LIFE: EXPANDING BEYOND GAMING
 
Curtain Module Manual Zigbee Neo CS01-1C.pdf
Curtain Module Manual Zigbee Neo CS01-1C.pdfCurtain Module Manual Zigbee Neo CS01-1C.pdf
Curtain Module Manual Zigbee Neo CS01-1C.pdf
 
Artificial-Intelligence-in-Marketing-Data.pdf
Artificial-Intelligence-in-Marketing-Data.pdfArtificial-Intelligence-in-Marketing-Data.pdf
Artificial-Intelligence-in-Marketing-Data.pdf
 
Z-Wave Fan coil Thermostat Heltun_HE-HT01_User_Manual.pdf
Z-Wave Fan coil Thermostat Heltun_HE-HT01_User_Manual.pdfZ-Wave Fan coil Thermostat Heltun_HE-HT01_User_Manual.pdf
Z-Wave Fan coil Thermostat Heltun_HE-HT01_User_Manual.pdf
 
Avoiding Bad Stats and the Benefits of Playing Trivia with Friends: PancakesC...
Avoiding Bad Stats and the Benefits of Playing Trivia with Friends: PancakesC...Avoiding Bad Stats and the Benefits of Playing Trivia with Friends: PancakesC...
Avoiding Bad Stats and the Benefits of Playing Trivia with Friends: PancakesC...
 
Bit N Build Poland
Bit N Build PolandBit N Build Poland
Bit N Build Poland
 
Q1 Memory Fabric Forum: Advantages of Optical CXL​ for Disaggregated Compute ...
Q1 Memory Fabric Forum: Advantages of Optical CXL​ for Disaggregated Compute ...Q1 Memory Fabric Forum: Advantages of Optical CXL​ for Disaggregated Compute ...
Q1 Memory Fabric Forum: Advantages of Optical CXL​ for Disaggregated Compute ...
 
2024 February Patch Tuesday
2024 February Patch Tuesday2024 February Patch Tuesday
2024 February Patch Tuesday
 
Q1 Memory Fabric Forum: SMART CXL Product Lineup
Q1 Memory Fabric Forum: SMART CXL Product LineupQ1 Memory Fabric Forum: SMART CXL Product Lineup
Q1 Memory Fabric Forum: SMART CXL Product Lineup
 

Lambdas in Java 8

  • 1. Lambdas in Java 8 Start programming in a more functional style
  • 2. Background Who am I? • Tobias Coetzee • I’m a Technical Lead at BBD • I present the Java Expert Level Certifications at BBD (EJB, JPA, etc.) • I’m currently a banker • Part of the JoziJug organising committee • I like to run • This presentation is based on a Simon Ritter course • @tobiascode • https://github.com/Jozi-JUG/lamdatraining
  • 3. ASK QUESTIONS, SWAG FOR EVERYONE!!
  • 4. Outcomes What are the take away’s? • Why should we care about lambdas • Apply lambdas to everyday problems • Determine when to apply lambdas (and when not to!) • How does the lambda syntax work? • What are functional interfaces? • Convert anonymous classes to lambda expressions • Debug lambda expressions
  • 6. Why lambdas? Why care about concurrency in Java? • CPU’s are getting much faster, but we are getting more cores to use. • We need to parallelise our processing. • The functional programming paradigm lends itself better to parallel processing as there is no external state. Concurrency history in Java • Java 1 had threads. • Java 5 had java.util.concurrent (BlockingQueue, Executers, etc.). • Java 7 had Fork/Join framework. • Java 8 gives us Lambdas.
  • 7. Demo: Intro to functional programming in Java 8
  • 8. When do we use lambdas? Usages • Inject functionality into methods, the same way we inject values into methods. • Look where methods are very similar except for 1 or 2 lines of code. • Look at streams for clues, filtering, mapping, finding, matching, etc. • Enhance library methods, look at new Collection methods. • Small one line functions. • To shorten your code, remove inner classes and anonymous classes. • If you want to use streams.
  • 9. When don’t we use lambdas? Non-Usages • Lambdas were introduced into Java for 2 reasons, to allow programming in a functional paradigm and to make code shorter and more concise. • If it isn’t used for one or both these reasons, rethink the usage. • Avoid huge lambdas, e.g. 20 lines of code. • Because it is cool!
  • 11. Lambda Syntax Basic Structure (parameters) -> {lambda body} Rules • Lambdas can be single or multi-line • Single line Lambdas • Do not need curly braces • Do not need an explicit return statement • Lambdas with a single parameter do not need braces • Lambdas with no parameters must have empty braces • Body of the Lambda may throw exceptions lambda operator
  • 12. Lambda Syntax Examples • () -> System.out.println("Hello Lambda") • x -> x + 10 • (int x, int y) -> { return x + y; } • (String x, String y) -> x.length() – y.length() • (String x) -> { listA.add(x); listB.remove(x); return listB.size(); } • (x, y) -> x.length() – y.length()
  • 15. Functional Interfaces Lambda Expression Types • A lambda expression is an anonymous function, it is not associated with a class. • A lambda expression can be used wherever the type is a functional interface. • This is a single abstract method type. • The lambda expression provides the implementation of the abstract method.
  • 16. Functional Interfaces Definition • An interface that has only one abstract method. • Before Java 8 this was obvious, only one method. • Java 8 introduced default methods • Multiple inheritance of behaviour for Java • Java 8 also now allows static methods in interfaces • @FunctionalInterface annotation • Previously known as SAM’s, Single Abstract Methods • java.lang.Runnable, java.awt.event.ActionListener, java.util.Comparator, java.util.concurrent.Callable
  • 17. True or False: Functional Interfaces
  • 18. Functional Interfaces Example Uses Of Lambda Expressions • Method parameter consumeStudent(s -> System.out.println(s.getGrade())); • Variable assignment Consumer<Student> c = s -> System.out.println(s.getGrade())
  • 19. Functional Interfaces java.util.function Package • Well defined set of general purpose functional interfaces. • All have only one abstract method. • Lambda expressions can be used wherever these types are referenced. • Used extensively in the Java class libraries. • Especially with the Stream API. • Includes several static methods to help with composing/chaining. • Variations on number of arguments and specific for primitive types.
  • 20. Functional Interfaces Supplied Interfaces Interface Description Consumer<T> Operation that takes a single value and returns no result. Supplier A supplier of results. Function<T,R> A function that accepts one argument and returns a result. UnaryOperator<T> Specialised form of function, takes a single argument and returns a result of the same type. BinaryOperator<T> Specialised form of function, takes two arguments and returns a result of the same type Predicate A boolean valued function that takes one argument.
  • 23. Method&Constructor References Usage • Method references let us reuse a method as a lambda expression. FileFilter x = File f -> f.canRead(); FileFilter x = File::canRead; • Format: target_reference::method_name • Three kinds of method reference • Static method • Instance method of an arbitrary type • Instance method of an existing object
  • 24. Method&Constructor References Rules For Construction (args) -> ClassName.staticMethod(args) ClassName::staticMethod (arg0, rest) -> arg0.instanceMethod(rest) ClassName::instanceMethod (args) -> expr.instanceMethod(args) expr::instanceMethod
  • 25. Method&Constructor References Constructor Reference • Same concept as a method reference. Factory<List<String>> f = () -> return new ArrayList<String>(); Factory<List<String>> f = ArrayList<String>::new;
  • 27. Referencing External Variables Effectively Final • Lambda expressions can refer to effectively final local variables from the surrounding scope. class DataProcessor { private int currentValue; public void process() { DataSet myData = myFactory.getDataSet(); dataSet.forEach(d -> d.use(currentValue++)); } }
  • 28. Referencing External Variables Effectively Final • Effectively final: A variable that meets the requirements for final variables (i.e., assigned once), even if not explicitly declared final. • Closures on values, not variables. • Closures allow you to use variables defined outside the scope of a function. • For heap-based objects, e.g. arrays, modify values just not reference.
  • 29. Referencing External Variables ‘this’ in a Lambda • 'this' refers to the enclosing object, not the lambda itself. • Remember the Lambda is an anonymous function. • It is not associated with a class, therefore there can be no 'this' for a lambda. class DataProcessor { private int currentValue; public void process() { DataSet myData = myFactory.getDataSet(); dataSet.forEach(d -> d.use(this.currentValue++)); } }
  • 31. Debugging Lambdas Problem • Lambda expressions do not compile to equivalent inner class. • Compiled to invokedynamic call. • Implementation decided at runtime. • Better chance of optimisation, makes debugging harder.
  • 32. Debugging Lambdas Solution • IDE should support debugging. • If not, extract the code from a lambda expression into a separate method. • Replace the lambda with a method reference for the new method. • Implement the functional interface and pass a reference of the class.
  • 34. New Lambda Methods in Java 8
  • 35. New Lambda Methods Why New Methods? • Look at existing interfaces for new default or static methods, they are normally the new methods that accept lambdas. • Use the new methods in Java 8 to eliminate the frequent need for loops. • Fits in with using the functional paradigm. • Remember that a lambda provides behaviour, not a value. • Very useful for conditional uses of data.
  • 36. Functional Interfaces Some examples Interface Description Iterable.forEach(Consumer c) myList.forEach(System.out::println); Collection.removeIf(Predicate p) myList.removeIf(s -> s.length() == 0); List.replaceAll(UnaryOperator o) myList.replaceAll(String::toUpperCase); List.sort(Comparator c) Replaces Collections.sort(List l, Comparator c) myList.sort((x, y) -> x.length() – y.length());
  • 38. Exercises How does it work? • The exercises for this month are all small exercises that you will complete using the things you have learned during this presentation. • There are 6 exercises to complete. • For first month focus on using lambda expressions, method references and some of the new methods that have been added to existing classes. • There is a template source file that you should use to create the answers to the exercises called Exercise_Test.java under the test folder. • To simplify things the lists and maps you need for the exercises have already been created. • You just need to focus on the code to solve the exercise. • The solutions are in the Solution_Test.java file, but try all the exercises first before taking a peak.