SlideShare a Scribd company logo
1 of 12
Extension Methods and Lambdas in Java 8 2011-03-03 Andreas Enbohm
3 mars 2011 Sida 2 Extension Methods Whathappenshere? people.sort(#Person.lastName)
Extension Methods Whatwehave in Java today… Toomuchnoise! Collections.sort(people, new Comparator() { 	@Override 	public intcompare(Person x, Person y) { returnx.getLastName().compareTo(y.getLastName()); 	} }); 3 mars 2011 Sida 3
SAM types and Lambdas Single Abstract Method (SAM) 3 mars 2011 Sida 4 Thread th = new Thread(new Runnable() {  		public void run() {  doSomeStuff();  doMoreStuff();        } }); //OLD WAY Thread th = new Thread(#(){  doSomeStuff();  doMoreStuff(); } )
3 mars 2011 Sida 5 SAM and Lambdas conversion With Lambdas and SAM it looks like Collections.sort(people, #{ Person x, Person y -> 			  x.getLastName().compareTo(y.getLastName()) }); //Old way, let’shopewesooncan @Deprecate this code Collections.sort(people, new Comparator() { 	@Override 	public intcompare(Person x, Person y) { returnx.getLastName().compareTo(y.getLastName()); 	} });
EnchancedLibraries (Collections) But it gets evenbetter with EnchancedLibraries 3 mars 2011 Sida 6 //Collections is updated. No need to specify Person x and  //Person y, just say ’take a person in the [list] and sort by //last name’ (its implicit that compareToshould be used) Collections.sortBy(people, #{ Person p -> p.getLastName() });
TypeInference …and with somehelp from the compiler…we get TypeInference 3 mars 2011 Sida 7 //No need to specify Person, the compilercan (often) helpus //with this. Compilerintrospectpeople-list via generics Collections.sortBy(people, #{ p -> p.getLastName() });
MethodReference A new feature with Project Lambdas is MethodReferenceswhich gives us… 3 mars 2011 Sida 8 //Methodreferenceallowsus to ’point’ directly to the method //wewant to use in oursorting. Whyuse a particularobject? Collections.sortBy(people, #Person.getLastName );
Extension Methods and with Extension Methodswefinally get… 3 mars 2011 Sida 9 //Nice, wehavepeople (a List<T>) whichcandosorting. But //wait a minuteList<T> don’thave a sort(…) method… Howdid //this work? people.sortBy( #Person.getLastName);
Extension Methods (DefenderMethods) A way to evolve interfaces WITHOUT breakingbinarybackwardscompatability. Means that wecanadd new methods in an existing interface and the implementingclientsdoes NOT need to implement that method! A reallyneed for updatingaging Collections interface, especiallywhen lambdas and Fork-Join are introduced in Java The interface willsupply a default implementationif you do not supplyoneyourself 3 mars 2011 Sida 10
Enhancedlibraries Proposed Syntax 3 mars 2011 Sida 11 public interface List<T> extends Collection<T> {     public intsize();     // The rest of the existing List methods     extensionvoid sort(List<T> list) default  Collections.<T>sort; }
3 mars 2011 Sida 12 Extension Methods Questions? people.eat(#Senadin.cake)

More Related Content

What's hot

Doubly linked list
Doubly linked listDoubly linked list
Doubly linked listFahd Allebdi
 
Data Structures and Algorithms
Data Structures and AlgorithmsData Structures and Algorithms
Data Structures and AlgorithmsSNEHAL MASNE
 
Incremental View Maintenance for openCypher Queries
Incremental View Maintenance for openCypher QueriesIncremental View Maintenance for openCypher Queries
Incremental View Maintenance for openCypher QueriesGábor Szárnyas
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked ListNinad Mankar
 
Progress Report 20091009
Progress Report 20091009Progress Report 20091009
Progress Report 20091009xoanon
 
Duplicate Detection in Hierarchical Data Using XPath
Duplicate Detection in Hierarchical Data Using XPathDuplicate Detection in Hierarchical Data Using XPath
Duplicate Detection in Hierarchical Data Using XPathiosrjce
 
Combining Inverted Indices and Structured Search for Ad-hoc Object Retrieval
Combining Inverted Indices and Structured Search for  Ad-hoc Object RetrievalCombining Inverted Indices and Structured Search for  Ad-hoc Object Retrieval
Combining Inverted Indices and Structured Search for Ad-hoc Object RetrievaleXascale Infolab
 
Basic Tutorial of Association Mapping by Avjinder Kaler
Basic Tutorial of Association Mapping by Avjinder KalerBasic Tutorial of Association Mapping by Avjinder Kaler
Basic Tutorial of Association Mapping by Avjinder KalerAvjinder (Avi) Kaler
 
Check my answer to pass data from one webform to the next, you ca
 Check my answer to pass data from one webform to the next, you ca Check my answer to pass data from one webform to the next, you ca
Check my answer to pass data from one webform to the next, you calicservernoida
 
ADT STACK and Queues
ADT STACK and QueuesADT STACK and Queues
ADT STACK and QueuesBHARATH KUMAR
 

What's hot (19)

Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
C Omega
C OmegaC Omega
C Omega
 
Doubly linked list
Doubly linked listDoubly linked list
Doubly linked list
 
Data Structures and Algorithms
Data Structures and AlgorithmsData Structures and Algorithms
Data Structures and Algorithms
 
Incremental View Maintenance for openCypher Queries
Incremental View Maintenance for openCypher QueriesIncremental View Maintenance for openCypher Queries
Incremental View Maintenance for openCypher Queries
 
Just Kotlin
Just KotlinJust Kotlin
Just Kotlin
 
Doubly Link List
Doubly Link ListDoubly Link List
Doubly Link List
 
Functional Concepts
Functional ConceptsFunctional Concepts
Functional Concepts
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
Progress Report 20091009
Progress Report 20091009Progress Report 20091009
Progress Report 20091009
 
linked list
linked list linked list
linked list
 
Introduction to r
Introduction to rIntroduction to r
Introduction to r
 
TRank ISWC2013
TRank ISWC2013TRank ISWC2013
TRank ISWC2013
 
Duplicate Detection in Hierarchical Data Using XPath
Duplicate Detection in Hierarchical Data Using XPathDuplicate Detection in Hierarchical Data Using XPath
Duplicate Detection in Hierarchical Data Using XPath
 
Combining Inverted Indices and Structured Search for Ad-hoc Object Retrieval
Combining Inverted Indices and Structured Search for  Ad-hoc Object RetrievalCombining Inverted Indices and Structured Search for  Ad-hoc Object Retrieval
Combining Inverted Indices and Structured Search for Ad-hoc Object Retrieval
 
Compiler design
Compiler designCompiler design
Compiler design
 
Basic Tutorial of Association Mapping by Avjinder Kaler
Basic Tutorial of Association Mapping by Avjinder KalerBasic Tutorial of Association Mapping by Avjinder Kaler
Basic Tutorial of Association Mapping by Avjinder Kaler
 
Check my answer to pass data from one webform to the next, you ca
 Check my answer to pass data from one webform to the next, you ca Check my answer to pass data from one webform to the next, you ca
Check my answer to pass data from one webform to the next, you ca
 
ADT STACK and Queues
ADT STACK and QueuesADT STACK and Queues
ADT STACK and Queues
 

Viewers also liked

Software Craftsmanship
Software CraftsmanshipSoftware Craftsmanship
Software CraftsmanshipAndreas Enbohm
 
BDD Short Introduction
BDD Short IntroductionBDD Short Introduction
BDD Short IntroductionAndreas Enbohm
 
Project Lambda - Closures after all?
Project Lambda - Closures after all?Project Lambda - Closures after all?
Project Lambda - Closures after all?Andreas Enbohm
 
Behavior-driven Development and Lambdaj
Behavior-driven Development and LambdajBehavior-driven Development and Lambdaj
Behavior-driven Development and LambdajAndreas Enbohm
 
Java7 - Top 10 Features
Java7 - Top 10 FeaturesJava7 - Top 10 Features
Java7 - Top 10 FeaturesAndreas Enbohm
 
SOLID Design Principles
SOLID Design PrinciplesSOLID Design Principles
SOLID Design PrinciplesAndreas Enbohm
 

Viewers also liked (8)

Software Craftsmanship
Software CraftsmanshipSoftware Craftsmanship
Software Craftsmanship
 
BDD Short Introduction
BDD Short IntroductionBDD Short Introduction
BDD Short Introduction
 
Scala
ScalaScala
Scala
 
Project Lambda - Closures after all?
Project Lambda - Closures after all?Project Lambda - Closures after all?
Project Lambda - Closures after all?
 
Behavior-driven Development and Lambdaj
Behavior-driven Development and LambdajBehavior-driven Development and Lambdaj
Behavior-driven Development and Lambdaj
 
Java7 - Top 10 Features
Java7 - Top 10 FeaturesJava7 - Top 10 Features
Java7 - Top 10 Features
 
Hybrid Applications
Hybrid ApplicationsHybrid Applications
Hybrid Applications
 
SOLID Design Principles
SOLID Design PrinciplesSOLID Design Principles
SOLID Design Principles
 

Similar to Java Extension Methods

Lambdas: Myths and Mistakes
Lambdas: Myths and MistakesLambdas: Myths and Mistakes
Lambdas: Myths and MistakesRichardWarburton
 
Data Science Academy Student Demo day--Michael blecher,the importance of clea...
Data Science Academy Student Demo day--Michael blecher,the importance of clea...Data Science Academy Student Demo day--Michael blecher,the importance of clea...
Data Science Academy Student Demo day--Michael blecher,the importance of clea...Vivian S. Zhang
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfkarymadelaneyrenne19
 
FUNctional Programming in Java 8
FUNctional Programming in Java 8FUNctional Programming in Java 8
FUNctional Programming in Java 8Richard Walker
 
This is the official tutorial from Oracle.httpdocs.oracle.comj.pdf
This is the official tutorial from Oracle.httpdocs.oracle.comj.pdfThis is the official tutorial from Oracle.httpdocs.oracle.comj.pdf
This is the official tutorial from Oracle.httpdocs.oracle.comj.pdfjillisacebi75827
 
computer notes - Data Structures - 5
computer notes - Data Structures - 5computer notes - Data Structures - 5
computer notes - Data Structures - 5ecomputernotes
 
Computer notes - Josephus Problem
Computer notes - Josephus ProblemComputer notes - Josephus Problem
Computer notes - Josephus Problemecomputernotes
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useSharon Rozinsky
 
Roberto Trasarti PhD Thesis
Roberto Trasarti PhD ThesisRoberto Trasarti PhD Thesis
Roberto Trasarti PhD ThesisRoberto Trasarti
 
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxLab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxsmile790243
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#Shahzad
 
myEquivalents, aka a new cross-reference service
myEquivalents, aka a new cross-reference servicemyEquivalents, aka a new cross-reference service
myEquivalents, aka a new cross-reference serviceRothamsted Research, UK
 
Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Philip Schwarz
 
computer notes - Circular list
computer notes - Circular listcomputer notes - Circular list
computer notes - Circular listecomputernotes
 
Introduction to the R Statistical Computing Environment
Introduction to the R Statistical Computing EnvironmentIntroduction to the R Statistical Computing Environment
Introduction to the R Statistical Computing Environmentizahn
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)mussawir20
 

Similar to Java Extension Methods (20)

Lambdas: Myths and Mistakes
Lambdas: Myths and MistakesLambdas: Myths and Mistakes
Lambdas: Myths and Mistakes
 
Data Science Academy Student Demo day--Michael blecher,the importance of clea...
Data Science Academy Student Demo day--Michael blecher,the importance of clea...Data Science Academy Student Demo day--Michael blecher,the importance of clea...
Data Science Academy Student Demo day--Michael blecher,the importance of clea...
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
 
FUNctional Programming in Java 8
FUNctional Programming in Java 8FUNctional Programming in Java 8
FUNctional Programming in Java 8
 
This is the official tutorial from Oracle.httpdocs.oracle.comj.pdf
This is the official tutorial from Oracle.httpdocs.oracle.comj.pdfThis is the official tutorial from Oracle.httpdocs.oracle.comj.pdf
This is the official tutorial from Oracle.httpdocs.oracle.comj.pdf
 
computer notes - Data Structures - 5
computer notes - Data Structures - 5computer notes - Data Structures - 5
computer notes - Data Structures - 5
 
Java 8 by example!
Java 8 by example!Java 8 by example!
Java 8 by example!
 
Computer notes - Josephus Problem
Computer notes - Josephus ProblemComputer notes - Josephus Problem
Computer notes - Josephus Problem
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
 
Invitation to Scala
Invitation to ScalaInvitation to Scala
Invitation to Scala
 
Roberto Trasarti PhD Thesis
Roberto Trasarti PhD ThesisRoberto Trasarti PhD Thesis
Roberto Trasarti PhD Thesis
 
Graphql
GraphqlGraphql
Graphql
 
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxLab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 
myEquivalents, aka a new cross-reference service
myEquivalents, aka a new cross-reference servicemyEquivalents, aka a new cross-reference service
myEquivalents, aka a new cross-reference service
 
Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Sequence and Traverse - Part 2
Sequence and Traverse - Part 2
 
Tolog Updates
Tolog UpdatesTolog Updates
Tolog Updates
 
computer notes - Circular list
computer notes - Circular listcomputer notes - Circular list
computer notes - Circular list
 
Introduction to the R Statistical Computing Environment
Introduction to the R Statistical Computing EnvironmentIntroduction to the R Statistical Computing Environment
Introduction to the R Statistical Computing Environment
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)
 

Recently uploaded

Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 

Recently uploaded (20)

Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 

Java Extension Methods

  • 1. Extension Methods and Lambdas in Java 8 2011-03-03 Andreas Enbohm
  • 2. 3 mars 2011 Sida 2 Extension Methods Whathappenshere? people.sort(#Person.lastName)
  • 3. Extension Methods Whatwehave in Java today… Toomuchnoise! Collections.sort(people, new Comparator() { @Override public intcompare(Person x, Person y) { returnx.getLastName().compareTo(y.getLastName()); } }); 3 mars 2011 Sida 3
  • 4. SAM types and Lambdas Single Abstract Method (SAM) 3 mars 2011 Sida 4 Thread th = new Thread(new Runnable() { public void run() { doSomeStuff(); doMoreStuff(); } }); //OLD WAY Thread th = new Thread(#(){ doSomeStuff(); doMoreStuff(); } )
  • 5. 3 mars 2011 Sida 5 SAM and Lambdas conversion With Lambdas and SAM it looks like Collections.sort(people, #{ Person x, Person y -> x.getLastName().compareTo(y.getLastName()) }); //Old way, let’shopewesooncan @Deprecate this code Collections.sort(people, new Comparator() { @Override public intcompare(Person x, Person y) { returnx.getLastName().compareTo(y.getLastName()); } });
  • 6. EnchancedLibraries (Collections) But it gets evenbetter with EnchancedLibraries 3 mars 2011 Sida 6 //Collections is updated. No need to specify Person x and //Person y, just say ’take a person in the [list] and sort by //last name’ (its implicit that compareToshould be used) Collections.sortBy(people, #{ Person p -> p.getLastName() });
  • 7. TypeInference …and with somehelp from the compiler…we get TypeInference 3 mars 2011 Sida 7 //No need to specify Person, the compilercan (often) helpus //with this. Compilerintrospectpeople-list via generics Collections.sortBy(people, #{ p -> p.getLastName() });
  • 8. MethodReference A new feature with Project Lambdas is MethodReferenceswhich gives us… 3 mars 2011 Sida 8 //Methodreferenceallowsus to ’point’ directly to the method //wewant to use in oursorting. Whyuse a particularobject? Collections.sortBy(people, #Person.getLastName );
  • 9. Extension Methods and with Extension Methodswefinally get… 3 mars 2011 Sida 9 //Nice, wehavepeople (a List<T>) whichcandosorting. But //wait a minuteList<T> don’thave a sort(…) method… Howdid //this work? people.sortBy( #Person.getLastName);
  • 10. Extension Methods (DefenderMethods) A way to evolve interfaces WITHOUT breakingbinarybackwardscompatability. Means that wecanadd new methods in an existing interface and the implementingclientsdoes NOT need to implement that method! A reallyneed for updatingaging Collections interface, especiallywhen lambdas and Fork-Join are introduced in Java The interface willsupply a default implementationif you do not supplyoneyourself 3 mars 2011 Sida 10
  • 11. Enhancedlibraries Proposed Syntax 3 mars 2011 Sida 11 public interface List<T> extends Collection<T> { public intsize(); // The rest of the existing List methods extensionvoid sort(List<T> list) default Collections.<T>sort; }
  • 12. 3 mars 2011 Sida 12 Extension Methods Questions? people.eat(#Senadin.cake)