SlideShare ist ein Scribd-Unternehmen logo
1 von 25
Downloaden Sie, um offline zu lesen
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!

Weitere ähnliche Inhalte

Was ist angesagt?

Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersBartosz Kosarzycki
 
How to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingHow to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingIndicThreads
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8Takipi
 
Refactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapDave Orme
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
Reactive Android: RxJava and beyond
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyondFabio Tiriticco
 
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
 
A Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaA Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaDerek Chen-Becker
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in actionCiro Rizzo
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Ganesh Samarthyam
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project LambdaRahman USTA
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New FeaturesNaveen Hegde
 

Was ist angesagt? (20)

Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
How to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingHow to Think in RxJava Before Reacting
How to Think in RxJava Before Reacting
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8
 
Refactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 Recap
 
Smart Migration to JDK 8
Smart Migration to JDK 8Smart Migration to JDK 8
Smart Migration to JDK 8
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Java 7 New Features
Java 7 New FeaturesJava 7 New Features
Java 7 New Features
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
 
Reactive Android: RxJava and beyond
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyond
 
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
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
A Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaA Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to Scala
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in action
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New Features
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 

Andere mochten auch

Closures: The Next "Big Thing" In Java
Closures: The Next "Big Thing" In JavaClosures: The Next "Big Thing" In Java
Closures: The Next "Big Thing" In JavaRussel Winder
 
Clojure: an overview
Clojure: an overviewClojure: an overview
Clojure: an overviewLarry Diehl
 
Implementing STM in Java
Implementing STM in JavaImplementing STM in Java
Implementing STM in JavaMisha Kozik
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronizationxuehan zhu
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developersJohn Stevenson
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with ClojureJohn Stevenson
 
Clojure: The Art of Abstraction
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of AbstractionAlex Miller
 
JVM上的实用Lisp方言:Clojure
JVM上的实用Lisp方言:ClojureJVM上的实用Lisp方言:Clojure
JVM上的实用Lisp方言:ClojureRui Peng
 

Andere mochten auch (10)

Closures: The Next "Big Thing" In Java
Closures: The Next "Big Thing" In JavaClosures: The Next "Big Thing" In Java
Closures: The Next "Big Thing" In Java
 
Clojure: an overview
Clojure: an overviewClojure: an overview
Clojure: an overview
 
Implementing STM in Java
Implementing STM in JavaImplementing STM in Java
Implementing STM in Java
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
 
ETL in Clojure
ETL in ClojureETL in Clojure
ETL in Clojure
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developers
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 
DSL in Clojure
DSL in ClojureDSL in Clojure
DSL in Clojure
 
Clojure: The Art of Abstraction
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of Abstraction
 
JVM上的实用Lisp方言:Clojure
JVM上的实用Lisp方言:ClojureJVM上的实用Lisp方言:Clojure
JVM上的实用Lisp方言:Clojure
 

Ähnlich wie Intro to Java 8 Closures (Dainius Mezanskas)

New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 itiAhmed mar3y
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of LambdasEsther Lozano
 
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
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016STX Next
 

Ähnlich wie Intro to Java 8 Closures (Dainius Mezanskas) (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
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
 
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
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
 

Mehr von Kaunas Java User Group

Mehr von Kaunas Java User Group (13)

Smart House Based on Raspberry PI + Java EE by Tadas Brasas
Smart House Based on Raspberry PI + Java EE by Tadas BrasasSmart House Based on Raspberry PI + Java EE by Tadas Brasas
Smart House Based on Raspberry PI + Java EE by Tadas Brasas
 
Presentation
PresentationPresentation
Presentation
 
Automated infrastructure
Automated infrastructureAutomated infrastructure
Automated infrastructure
 
Adf presentation
Adf presentationAdf presentation
Adf presentation
 
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)Bye Bye Cowboy Coder Days! (Legacy Code & TDD)
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)
 
Building with Gradle
Building with GradleBuilding with Gradle
Building with Gradle
 
Flyway
FlywayFlyway
Flyway
 
Eh cache in Kaunas JUG
Eh cache in Kaunas JUGEh cache in Kaunas JUG
Eh cache in Kaunas JUG
 
Apache Lucene Informacijos paieška
Apache Lucene Informacijos paieška Apache Lucene Informacijos paieška
Apache Lucene Informacijos paieška
 
Java 8 Stream API (Valdas Zigas)
Java 8 Stream API (Valdas Zigas)Java 8 Stream API (Valdas Zigas)
Java 8 Stream API (Valdas Zigas)
 
Kaunas JUG#1: Intro (Valdas Zigas)
Kaunas JUG#1: Intro (Valdas Zigas)Kaunas JUG#1: Intro (Valdas Zigas)
Kaunas JUG#1: Intro (Valdas Zigas)
 
Kaunas JUG#1: Java History and Trends (Dainius Mezanskas)
Kaunas JUG#1: Java History and Trends (Dainius Mezanskas)Kaunas JUG#1: Java History and Trends (Dainius Mezanskas)
Kaunas JUG#1: Java History and Trends (Dainius Mezanskas)
 
Kaunas JUG#2: Devoxx 2013 (Saulius Tvarijonas)
Kaunas JUG#2: Devoxx 2013 (Saulius Tvarijonas)Kaunas JUG#2: Devoxx 2013 (Saulius Tvarijonas)
Kaunas JUG#2: Devoxx 2013 (Saulius Tvarijonas)
 

Kürzlich hochgeladen

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 

Kürzlich hochgeladen (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 

Intro to Java 8 Closures (Dainius Mezanskas)

  • 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