SlideShare a Scribd company logo
1 of 25
Download to read offline
Java 8
Intro to Closures (Laλλbdas)
Kaunas JUG
Dainius Mežanskas · kaunas.jug@gmail.com · http://plus.google.com/+KaunasJUG
{ λ }
Dainius Mežanskas
● 16 years of Java
● Java SE/EE
● e-Learning · Insurance · Telecommunications ·
e-Commerce
● KTU DMC · Exigen Group · NoMagic Europe ·
Modnique Baltic
Presentation Source Code
https://github.com/dainiusm/kaunasjug2lambdas.git
What is Lambda? (aka. Closure)
● Anonymous function in
programming
● Provides a way to write
closures
Closure
function adder() {
def x = 0;
function incrementX() {
x = x + 1;
return x;
}
return incrementX;
}
def y = adder(); // Ref to closure
y(); // returns 1 (y.x == 0 + 1)
y(); // returns 2 (y.x == 1 + 1)
Why Lambda in Java
● 1 line instead of 5
● Functional programming
● References to methods
● Conciser collections API
● Streams · Filter/map/reduce
...
Functional Interface
● Single Abstract Method Interfaces (SAM)
● java.lang.Runnable, java.awt.event.ActionListener, java.util.
Comparator, java.util.concurrent.Callable etc.
● From JavaTM
8 - Functional interfaces
@FunctionalInterface (1)
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
@FunctionalInterface (2)
@FunctionalInterface
public interface Builder {
public abstract void build();
public abstract String toString();
}
@FunctionalInterface (3)
@FunctionalInterface
public interface Builder {
public abstract void build();
public abstract boolean isTrusted();
}
@FunctionalInterface (4)
@FunctionalInterface
public interface Builder {
public abstract void build();
public default boolean isTrusted() { return false; }
}
@FunctionalInterface (5)
@FunctionalInterface
public interface Builder {
public abstract void build();
public abstract String toString();
public default boolean isTrusted() { return false; }
public static Builder empty() { return () -> {}; }
} Builder.java
Lambda Syntax
● Argument List - zero or more
● Body - a single expression or a statement block
Argument List Arrow Token Body
(int a, int b) -> a + b
Lambda Examples
(int x, int y) -> x + y
() -> 42
a -> { return a * a; }
(a) -> a * a
(String s) -> { System.out.println(s); }
Comparator<String> c = (s1, s2) -> s1.compareTo(s2);
public class RunnableLambda {
public static void main(String[] args) {
Runnable runAnonymous = new Runnable() {
public void run() {
System.out.println("Anonymous Class Thread!");
}
};
Runnable runLmbd = () -> System.out.println("Lambda Thread!");
new Thread(runAnonymous).start();
new Thread(runLmbd).start();
}
}
RunnableLambda
RunnableLambda.java
List<String> vegetables =
Arrays.asList( "Carrot", "Watercress", "Dill", "Pea" );
Collections.sort( vegetables,
(String s1, String s2) -> { return -s1.compareTo(s2); } );
Collections.sort( vegetables,
(s1, s2) -> -s1.compareTo(s2)
);
System.out.println( vegetables );
ComparatorLambda
ComparatorLambda.java
CustomInterface
Lambda
public static void main(String[] args) {
Artist artist = new Artist();
artist.perform(
() -> System.out.println("Hello, Lambda")
);
}
@FunctionalInterface
interface Action {
void process();
}
class Artist {
public void perform(Action action) {
action.process();
}
} SimpleLambda.java
java.util.function
● Consumer<T> / void accept(T t);
● Function<T, R> / R apply(T t);
● blahOperator / ~vary~
● Predicate<T> / boolean test(T t);
● Supplier<T> / T get();
FunctionLambda.java
Lambda.this · Object = · final
● () -> { print(this); } // this == outer object
● Object n = () -> { print(“Wow!”)}; // compile fails
● Outer scope variables · final
(“effectively final”)
ThisLambda.java
ObjectLambda.java
FinalLambda.java
Default Methods
● Aka. Virtual Extension Methods or Defender Methods
● Inspired by Limitations designing Java 8 Collection API
with Lambdas
● IMHO For very basic/general/specific implementation
● May be inherited
DefaultMethodInheritance.java
List.forEach()
public interface Iterable<T> {
.....
default void forEach(Consumer action) {
for (T t : this) {
action.accept(t);
}
}
CollectionsBulkAndStream.java
Collections API additions
● Iterable.forEach(Consumer)
● Iterator.forEachRemaining(Consumer)
● Collection.removeIf(Predicate)
● Collection.spliterator()
● Collection.stream()
● Collection.parallelStream()
● List.sort(Comparator)
● List.replaceAll(UnaryOperator)
● Map.forEach(BiConsumer)
● Map.replaceAll(BiFunction)
● Map.putIfAbsent(K, V)
● Map.remove(Object, Object)
● Map.replace(K, V, V)
● Map.replace(K, V)
● Map.computeIfAbsent(K, Function)
● Map.computeIfPresent(K, BiFunction)
● Map.compute(K, BiFunction)
● Map.merge(K, V, BiFunction)
● Map.getOrDefault(Object, V)
Method References
Method
String::valueOf
Object::toString
x::toString
ArrayList::new
Lambda
x -> String.valueOf(x)
x -> x.toString()
() -> x.toString()
() -> new ArrayList<>()
->
MethodReferences.java
Streams
● Filter-Map-Reduce
● Infinite and stateful
● Sequential or parallel
● One or more intermediate operations
filter, map, flatMap, peel, distinct, sorted, limit, and substream
● One final terminal operation
forEach, toArray, reduce, collect, min, max, count, anyMatch, allMatch, noneMatch, findFirst, and findAny
Happy Birthday Java 8!

More Related Content

What's hot

Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engineDuoyi Wu
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive CocoaSmartLogic
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the webMichiel Borkent
 
jimmy hacking (at) Microsoft
jimmy hacking (at) Microsoftjimmy hacking (at) Microsoft
jimmy hacking (at) MicrosoftJimmy Schementi
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6Solution4Future
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Nilesh Jayanandana
 
JavaOne報告会 Java SE/JavaFX 編 - JJUG CCC 2010 Fall
JavaOne報告会 Java SE/JavaFX 編 - JJUG CCC 2010 FallJavaOne報告会 Java SE/JavaFX 編 - JJUG CCC 2010 Fall
JavaOne報告会 Java SE/JavaFX 編 - JJUG CCC 2010 FallYuichi Sakuraba
 
Dagger & rxjava & retrofit
Dagger & rxjava & retrofitDagger & rxjava & retrofit
Dagger & rxjava & retrofitTed Liang
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJSFunctional Reactive Programming with RxJS
Functional Reactive Programming with RxJSstefanmayer13
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015NAVER / MusicPlatform
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015Michiel Borkent
 
Preparation for mit ose lab4
Preparation for mit ose lab4Preparation for mit ose lab4
Preparation for mit ose lab4Benux Wei
 
Gaucheで本を作る
Gaucheで本を作るGaucheで本を作る
Gaucheで本を作るguest7a66b8
 
オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)Takayuki Goto
 

What's hot (20)

RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engine
 
Kotlin wonderland
Kotlin wonderlandKotlin wonderland
Kotlin wonderland
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
 
ECMAScript 2015 Tips & Traps
ECMAScript 2015 Tips & TrapsECMAScript 2015 Tips & Traps
ECMAScript 2015 Tips & Traps
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the web
 
Full Stack Clojure
Full Stack ClojureFull Stack Clojure
Full Stack Clojure
 
jimmy hacking (at) Microsoft
jimmy hacking (at) Microsoftjimmy hacking (at) Microsoft
jimmy hacking (at) Microsoft
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6
 
JavaOne報告会 Java SE/JavaFX 編 - JJUG CCC 2010 Fall
JavaOne報告会 Java SE/JavaFX 編 - JJUG CCC 2010 FallJavaOne報告会 Java SE/JavaFX 編 - JJUG CCC 2010 Fall
JavaOne報告会 Java SE/JavaFX 編 - JJUG CCC 2010 Fall
 
Dagger & rxjava & retrofit
Dagger & rxjava & retrofitDagger & rxjava & retrofit
Dagger & rxjava & retrofit
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJSFunctional Reactive Programming with RxJS
Functional Reactive Programming with RxJS
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
Meetup slides
Meetup slidesMeetup slides
Meetup slides
 
Preparation for mit ose lab4
Preparation for mit ose lab4Preparation for mit ose lab4
Preparation for mit ose lab4
 
Gaucheで本を作る
Gaucheで本を作るGaucheで本を作る
Gaucheで本を作る
 
Angular2 rxjs
Angular2 rxjsAngular2 rxjs
Angular2 rxjs
 
オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)
 

Viewers also liked

2015 s. stürmer innovations and new modes of
2015 s. stürmer innovations and new modes of2015 s. stürmer innovations and new modes of
2015 s. stürmer innovations and new modes ofEADTU
 
Roteiro de estudos Capítulo 3: Introdução ao Pentateuco
Roteiro de estudos Capítulo 3: Introdução ao PentateucoRoteiro de estudos Capítulo 3: Introdução ao Pentateuco
Roteiro de estudos Capítulo 3: Introdução ao PentateucoAmor pela EBD
 
Resenha pr gesieloliveira_dolivro-quanto-vale-quem-voce-ama-silmar-coelho
Resenha pr gesieloliveira_dolivro-quanto-vale-quem-voce-ama-silmar-coelhoResenha pr gesieloliveira_dolivro-quanto-vale-quem-voce-ama-silmar-coelho
Resenha pr gesieloliveira_dolivro-quanto-vale-quem-voce-ama-silmar-coelhoGesiel Oliveira
 
Problema resuelto de una disolución de etanol
Problema resuelto de una disolución de etanolProblema resuelto de una disolución de etanol
Problema resuelto de una disolución de etanolDiego Martín Núñez
 
Problema resuelto de una disolución de h2 so4
Problema resuelto de una disolución de h2 so4Problema resuelto de una disolución de h2 so4
Problema resuelto de una disolución de h2 so4Diego Martín Núñez
 
Problema de cinemática autobús va a la estación
Problema de cinemática autobús va a la estaciónProblema de cinemática autobús va a la estación
Problema de cinemática autobús va a la estaciónDiego Martín Núñez
 
Euclid powerpoint
Euclid powerpointEuclid powerpoint
Euclid powerpoint41497777
 
César vallejo
César  vallejoCésar  vallejo
César vallejoyesseniary
 

Viewers also liked (12)

2015 s. stürmer innovations and new modes of
2015 s. stürmer innovations and new modes of2015 s. stürmer innovations and new modes of
2015 s. stürmer innovations and new modes of
 
Presentación1
Presentación1Presentación1
Presentación1
 
Biografía de césar vallejo
Biografía de césar vallejoBiografía de césar vallejo
Biografía de césar vallejo
 
Roteiro de estudos Capítulo 3: Introdução ao Pentateuco
Roteiro de estudos Capítulo 3: Introdução ao PentateucoRoteiro de estudos Capítulo 3: Introdução ao Pentateuco
Roteiro de estudos Capítulo 3: Introdução ao Pentateuco
 
Análisis sintáctico
Análisis sintácticoAnálisis sintáctico
Análisis sintáctico
 
Resenha pr gesieloliveira_dolivro-quanto-vale-quem-voce-ama-silmar-coelho
Resenha pr gesieloliveira_dolivro-quanto-vale-quem-voce-ama-silmar-coelhoResenha pr gesieloliveira_dolivro-quanto-vale-quem-voce-ama-silmar-coelho
Resenha pr gesieloliveira_dolivro-quanto-vale-quem-voce-ama-silmar-coelho
 
Matt Stranghoener
Matt StranghoenerMatt Stranghoener
Matt Stranghoener
 
Problema resuelto de una disolución de etanol
Problema resuelto de una disolución de etanolProblema resuelto de una disolución de etanol
Problema resuelto de una disolución de etanol
 
Problema resuelto de una disolución de h2 so4
Problema resuelto de una disolución de h2 so4Problema resuelto de una disolución de h2 so4
Problema resuelto de una disolución de h2 so4
 
Problema de cinemática autobús va a la estación
Problema de cinemática autobús va a la estaciónProblema de cinemática autobús va a la estación
Problema de cinemática autobús va a la estación
 
Euclid powerpoint
Euclid powerpointEuclid powerpoint
Euclid powerpoint
 
César vallejo
César  vallejoCésar  vallejo
César vallejo
 

Similar to Intro to Java 8 Lambdas

New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 itiAhmed mar3y
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIGanesh Samarthyam
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and MonoidsHugo Gävert
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Lambda выражения и Java 8
Lambda выражения и Java 8Lambda выражения и Java 8
Lambda выражения и Java 8Alex Tumanoff
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrencykshanth2101
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in java 8 Dori Waldman
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdasshinolajla
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 

Similar to Intro to Java 8 Lambdas (20)

New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Java 8
Java 8Java 8
Java 8
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Lambda выражения и Java 8
Lambda выражения и Java 8Lambda выражения и Java 8
Lambda выражения и Java 8
 
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in java 8
 
What`s New in Java 8
What`s New in Java 8What`s New in Java 8
What`s New in Java 8
 
Kotlin
KotlinKotlin
Kotlin
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 

Recently uploaded

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 

Recently uploaded (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 

Intro to Java 8 Lambdas

  • 1. Java 8 Intro to Closures (Laλλbdas) Kaunas JUG Dainius Mežanskas · kaunas.jug@gmail.com · http://plus.google.com/+KaunasJUG { λ }
  • 2. Dainius Mežanskas ● 16 years of Java ● Java SE/EE ● e-Learning · Insurance · Telecommunications · e-Commerce ● KTU DMC · Exigen Group · NoMagic Europe · Modnique Baltic
  • 4. What is Lambda? (aka. Closure) ● Anonymous function in programming ● Provides a way to write closures
  • 5. Closure function adder() { def x = 0; function incrementX() { x = x + 1; return x; } return incrementX; } def y = adder(); // Ref to closure y(); // returns 1 (y.x == 0 + 1) y(); // returns 2 (y.x == 1 + 1)
  • 6. Why Lambda in Java ● 1 line instead of 5 ● Functional programming ● References to methods ● Conciser collections API ● Streams · Filter/map/reduce ...
  • 7. Functional Interface ● Single Abstract Method Interfaces (SAM) ● java.lang.Runnable, java.awt.event.ActionListener, java.util. Comparator, java.util.concurrent.Callable etc. ● From JavaTM 8 - Functional interfaces
  • 8. @FunctionalInterface (1) @FunctionalInterface public interface Runnable { public abstract void run(); }
  • 9. @FunctionalInterface (2) @FunctionalInterface public interface Builder { public abstract void build(); public abstract String toString(); }
  • 10. @FunctionalInterface (3) @FunctionalInterface public interface Builder { public abstract void build(); public abstract boolean isTrusted(); }
  • 11. @FunctionalInterface (4) @FunctionalInterface public interface Builder { public abstract void build(); public default boolean isTrusted() { return false; } }
  • 12. @FunctionalInterface (5) @FunctionalInterface public interface Builder { public abstract void build(); public abstract String toString(); public default boolean isTrusted() { return false; } public static Builder empty() { return () -> {}; } } Builder.java
  • 13. Lambda Syntax ● Argument List - zero or more ● Body - a single expression or a statement block Argument List Arrow Token Body (int a, int b) -> a + b
  • 14. Lambda Examples (int x, int y) -> x + y () -> 42 a -> { return a * a; } (a) -> a * a (String s) -> { System.out.println(s); } Comparator<String> c = (s1, s2) -> s1.compareTo(s2);
  • 15. public class RunnableLambda { public static void main(String[] args) { Runnable runAnonymous = new Runnable() { public void run() { System.out.println("Anonymous Class Thread!"); } }; Runnable runLmbd = () -> System.out.println("Lambda Thread!"); new Thread(runAnonymous).start(); new Thread(runLmbd).start(); } } RunnableLambda RunnableLambda.java
  • 16. List<String> vegetables = Arrays.asList( "Carrot", "Watercress", "Dill", "Pea" ); Collections.sort( vegetables, (String s1, String s2) -> { return -s1.compareTo(s2); } ); Collections.sort( vegetables, (s1, s2) -> -s1.compareTo(s2) ); System.out.println( vegetables ); ComparatorLambda ComparatorLambda.java
  • 17. CustomInterface Lambda public static void main(String[] args) { Artist artist = new Artist(); artist.perform( () -> System.out.println("Hello, Lambda") ); } @FunctionalInterface interface Action { void process(); } class Artist { public void perform(Action action) { action.process(); } } SimpleLambda.java
  • 18. java.util.function ● Consumer<T> / void accept(T t); ● Function<T, R> / R apply(T t); ● blahOperator / ~vary~ ● Predicate<T> / boolean test(T t); ● Supplier<T> / T get(); FunctionLambda.java
  • 19. Lambda.this · Object = · final ● () -> { print(this); } // this == outer object ● Object n = () -> { print(“Wow!”)}; // compile fails ● Outer scope variables · final (“effectively final”) ThisLambda.java ObjectLambda.java FinalLambda.java
  • 20. Default Methods ● Aka. Virtual Extension Methods or Defender Methods ● Inspired by Limitations designing Java 8 Collection API with Lambdas ● IMHO For very basic/general/specific implementation ● May be inherited DefaultMethodInheritance.java
  • 21. List.forEach() public interface Iterable<T> { ..... default void forEach(Consumer action) { for (T t : this) { action.accept(t); } } CollectionsBulkAndStream.java
  • 22. Collections API additions ● Iterable.forEach(Consumer) ● Iterator.forEachRemaining(Consumer) ● Collection.removeIf(Predicate) ● Collection.spliterator() ● Collection.stream() ● Collection.parallelStream() ● List.sort(Comparator) ● List.replaceAll(UnaryOperator) ● Map.forEach(BiConsumer) ● Map.replaceAll(BiFunction) ● Map.putIfAbsent(K, V) ● Map.remove(Object, Object) ● Map.replace(K, V, V) ● Map.replace(K, V) ● Map.computeIfAbsent(K, Function) ● Map.computeIfPresent(K, BiFunction) ● Map.compute(K, BiFunction) ● Map.merge(K, V, BiFunction) ● Map.getOrDefault(Object, V)
  • 23. Method References Method String::valueOf Object::toString x::toString ArrayList::new Lambda x -> String.valueOf(x) x -> x.toString() () -> x.toString() () -> new ArrayList<>() -> MethodReferences.java
  • 24. Streams ● Filter-Map-Reduce ● Infinite and stateful ● Sequential or parallel ● One or more intermediate operations filter, map, flatMap, peel, distinct, sorted, limit, and substream ● One final terminal operation forEach, toArray, reduce, collect, min, max, count, anyMatch, allMatch, noneMatch, findFirst, and findAny