Intro to Java 8 Closures (Dainius Mezanskas)

Kaunas Java User Group
Kaunas Java User GroupSenior Java Software Engineer at Kaunas Java User Group
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!
1 of 25

Recommended

Functional java 8 by
Functional java 8Functional java 8
Functional java 8nick_maiorano
2K views75 slides
Scala coated JVM by
Scala coated JVMScala coated JVM
Scala coated JVMStuart Roebuck
999 views24 slides
Modern Java Workshop by
Modern Java WorkshopModern Java Workshop
Modern Java WorkshopSimon Ritter
252 views68 slides
camel-scala.pdf by
camel-scala.pdfcamel-scala.pdf
camel-scala.pdfHiroshi Ono
470 views35 slides
Introduction to Java 8 by
Introduction to Java 8Introduction to Java 8
Introduction to Java 8Knoldus Inc.
4.1K views50 slides
Java 8 Feature Preview by
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature PreviewJim Bethancourt
522 views51 slides

More Related Content

What's hot

Kotlin advanced - language reference for android developers by
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersBartosz Kosarzycki
5.7K views36 slides
Java 8 features by
Java 8 featuresJava 8 features
Java 8 featuresNexThoughts Technologies
5.9K views69 slides
How to Think in RxJava Before Reacting by
How to Think in RxJava Before ReactingHow to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingIndicThreads
999 views71 slides
The Dark Side Of Lambda Expressions in Java 8 by
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
54.4K views23 slides
Refactoring to Scala DSLs and LiftOff 2009 Recap by
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapDave Orme
1.2K views53 slides
Smart Migration to JDK 8 by
Smart Migration to JDK 8Smart Migration to JDK 8
Smart Migration to JDK 8Geertjan Wielenga
16.5K views25 slides

What's hot(20)

Kotlin advanced - language reference for android developers by Bartosz Kosarzycki
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
Bartosz Kosarzycki5.7K views
How to Think in RxJava Before Reacting by IndicThreads
How to Think in RxJava Before ReactingHow to Think in RxJava Before Reacting
How to Think in RxJava Before Reacting
IndicThreads999 views
The Dark Side Of Lambda Expressions in Java 8 by Takipi
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
Takipi54.4K views
Refactoring to Scala DSLs and LiftOff 2009 Recap by Dave Orme
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 Recap
Dave Orme1.2K views
New Features in JDK 8 by Martin Toshev
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
Martin Toshev19.2K views
Reactive Android: RxJava and beyond by Fabio Tiriticco
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyond
Fabio Tiriticco471 views
Modern Programming in Java 8 - Lambdas, Streams and Date Time API by Ganesh Samarthyam
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
Ganesh Samarthyam9.4K views
Kotlin in action by Ciro Rizzo
Kotlin in actionKotlin in action
Kotlin in action
Ciro Rizzo3.7K views
Productive Programming in Java 8 - with Lambdas and Streams by Ganesh Samarthyam
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 Samarthyam11.7K views
Java 8 - Project Lambda by Rahman USTA
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
Rahman USTA5K views
Java SE 8 - New Features by Naveen Hegde
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New Features
Naveen Hegde1.6K views

Viewers also liked

Closures: The Next "Big Thing" In Java by
Closures: The Next "Big Thing" In JavaClosures: The Next "Big Thing" In Java
Closures: The Next "Big Thing" In JavaRussel Winder
1.1K views82 slides
Clojure: an overview by
Clojure: an overviewClojure: an overview
Clojure: an overviewLarry Diehl
1K views10 slides
Implementing STM in Java by
Implementing STM in JavaImplementing STM in Java
Implementing STM in JavaMisha Kozik
5.3K views69 slides
[Java concurrency]02.basic thread synchronization by
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronizationxuehan zhu
671 views74 slides
ETL in Clojure by
ETL in ClojureETL in Clojure
ETL in ClojureDmitriy Morozov
3.6K views49 slides
Clojure for Java developers by
Clojure for Java developersClojure for Java developers
Clojure for Java developersJohn Stevenson
3.2K views80 slides

Viewers also liked(10)

Closures: The Next "Big Thing" In Java by Russel Winder
Closures: The Next "Big Thing" In JavaClosures: The Next "Big Thing" In Java
Closures: The Next "Big Thing" In Java
Russel Winder1.1K views
Clojure: an overview by Larry Diehl
Clojure: an overviewClojure: an overview
Clojure: an overview
Larry Diehl1K views
Implementing STM in Java by Misha Kozik
Implementing STM in JavaImplementing STM in Java
Implementing STM in Java
Misha Kozik5.3K views
[Java concurrency]02.basic thread synchronization by xuehan zhu
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
xuehan zhu671 views
Clojure for Java developers by John Stevenson
Clojure for Java developersClojure for Java developers
Clojure for Java developers
John Stevenson3.2K views
Getting started with Clojure by John Stevenson
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
John Stevenson1.7K views
DSL in Clojure by Misha Kozik
DSL in ClojureDSL in Clojure
DSL in Clojure
Misha Kozik3.5K views
Clojure: The Art of Abstraction by Alex Miller
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of Abstraction
Alex Miller7.5K views
JVM上的实用Lisp方言:Clojure by Rui Peng
JVM上的实用Lisp方言:ClojureJVM上的实用Lisp方言:Clojure
JVM上的实用Lisp方言:Clojure
Rui Peng7.2K views

Similar to Intro to Java 8 Closures (Dainius Mezanskas)

New features in jdk8 iti by
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 itiAhmed mar3y
79 views59 slides
Lambdas puzzler - Peter Lawrey by
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyJAXLondon_Conference
673 views47 slides
Java 8 by
Java 8Java 8
Java 8vilniusjug
2.4K views78 slides
The... Wonderful? World of Lambdas by
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of LambdasEsther Lozano
504 views63 slides
Scala is java8.next() by
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
3.8K views122 slides
Introduction to Scalding and Monoids by
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and MonoidsHugo Gävert
7.6K views23 slides

Similar to Intro to Java 8 Closures (Dainius Mezanskas)(20)

New features in jdk8 iti by Ahmed mar3y
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
Ahmed mar3y79 views
The... Wonderful? World of Lambdas by Esther Lozano
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
Esther Lozano504 views
Scala is java8.next() by daewon jeong
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
daewon jeong3.8K views
Introduction to Scalding and Monoids by Hugo Gävert
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
Hugo Gävert7.6K views
Java 8 Workshop by Mario Fusco
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco7.4K views
FP in Java - Project Lambda and beyond by Mario Fusco
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco18.4K views
Lambda выражения и Java 8 by Alex Tumanoff
Lambda выражения и Java 8Lambda выражения и Java 8
Lambda выражения и Java 8
Alex Tumanoff4.3K views
What is new in java 8 concurrency by kshanth2101
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
kshanth2101458 views
whats new in java 8 by Dori Waldman
whats new in java 8 whats new in java 8
whats new in java 8
Dori Waldman535 views
What can be done with Java, but should better be done with Erlang (@pavlobaron) by Pavlo Baron
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 Baron2.2K views
20160520 what youneedtoknowaboutlambdas by shinolajla
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas
shinolajla971 views
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016 by STX Next
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
STX Next820 views
Kotlin Developer Starter in Android projects by Bartosz Kosarzycki
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki5.1K views

More from Kaunas Java User Group

Smart House Based on Raspberry PI + Java EE by Tadas Brasas by
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 BrasasKaunas Java User Group
469 views19 slides
Presentation by
PresentationPresentation
PresentationKaunas Java User Group
614 views12 slides
Automated infrastructure by
Automated infrastructureAutomated infrastructure
Automated infrastructureKaunas Java User Group
785 views34 slides
Adf presentation by
Adf presentationAdf presentation
Adf presentationKaunas Java User Group
1.4K views1 slide
Bye Bye Cowboy Coder Days! (Legacy Code & TDD) by
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)Bye Bye Cowboy Coder Days! (Legacy Code & TDD)
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)Kaunas Java User Group
1.3K views34 slides
Building with Gradle by
Building with GradleBuilding with Gradle
Building with GradleKaunas Java User Group
1.7K views17 slides

More from Kaunas Java User Group(13)

Recently uploaded

Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P... by
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...ShapeBlue
120 views62 slides
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue by
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlueCloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlueShapeBlue
68 views13 slides
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T by
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&TCloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&TShapeBlue
81 views34 slides
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates by
Keynote Talk: Open Source is Not Dead - Charles Schulz - VatesKeynote Talk: Open Source is Not Dead - Charles Schulz - Vates
Keynote Talk: Open Source is Not Dead - Charles Schulz - VatesShapeBlue
178 views15 slides
Digital Personal Data Protection (DPDP) Practical Approach For CISOs by
Digital Personal Data Protection (DPDP) Practical Approach For CISOsDigital Personal Data Protection (DPDP) Practical Approach For CISOs
Digital Personal Data Protection (DPDP) Practical Approach For CISOsPriyanka Aash
103 views59 slides
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas... by
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...Bernd Ruecker
50 views69 slides

Recently uploaded(20)

Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P... by ShapeBlue
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...
ShapeBlue120 views
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue by ShapeBlue
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlueCloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue
ShapeBlue68 views
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T by ShapeBlue
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&TCloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T
ShapeBlue81 views
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates by ShapeBlue
Keynote Talk: Open Source is Not Dead - Charles Schulz - VatesKeynote Talk: Open Source is Not Dead - Charles Schulz - Vates
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates
ShapeBlue178 views
Digital Personal Data Protection (DPDP) Practical Approach For CISOs by Priyanka Aash
Digital Personal Data Protection (DPDP) Practical Approach For CISOsDigital Personal Data Protection (DPDP) Practical Approach For CISOs
Digital Personal Data Protection (DPDP) Practical Approach For CISOs
Priyanka Aash103 views
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas... by Bernd Ruecker
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
Bernd Ruecker50 views
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R... by ShapeBlue
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...
ShapeBlue105 views
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue by ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlueElevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
ShapeBlue149 views
Business Analyst Series 2023 - Week 4 Session 7 by DianaGray10
Business Analyst Series 2023 -  Week 4 Session 7Business Analyst Series 2023 -  Week 4 Session 7
Business Analyst Series 2023 - Week 4 Session 7
DianaGray10110 views
Webinar : Desperately Seeking Transformation - Part 2: Insights from leading... by The Digital Insurer
Webinar : Desperately Seeking Transformation - Part 2:  Insights from leading...Webinar : Desperately Seeking Transformation - Part 2:  Insights from leading...
Webinar : Desperately Seeking Transformation - Part 2: Insights from leading...
"Surviving highload with Node.js", Andrii Shumada by Fwdays
"Surviving highload with Node.js", Andrii Shumada "Surviving highload with Node.js", Andrii Shumada
"Surviving highload with Node.js", Andrii Shumada
Fwdays49 views
Why and How CloudStack at weSystems - Stephan Bienek - weSystems by ShapeBlue
Why and How CloudStack at weSystems - Stephan Bienek - weSystemsWhy and How CloudStack at weSystems - Stephan Bienek - weSystems
Why and How CloudStack at weSystems - Stephan Bienek - weSystems
ShapeBlue172 views
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti... by ShapeBlue
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
ShapeBlue69 views
DRBD Deep Dive - Philipp Reisner - LINBIT by ShapeBlue
DRBD Deep Dive - Philipp Reisner - LINBITDRBD Deep Dive - Philipp Reisner - LINBIT
DRBD Deep Dive - Philipp Reisner - LINBIT
ShapeBlue110 views
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue by ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueWhat’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
ShapeBlue191 views
The Power of Heat Decarbonisation Plans in the Built Environment by IES VE
The Power of Heat Decarbonisation Plans in the Built EnvironmentThe Power of Heat Decarbonisation Plans in the Built Environment
The Power of Heat Decarbonisation Plans in the Built Environment
IES VE67 views
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ... by ShapeBlue
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...
ShapeBlue114 views
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or... by ShapeBlue
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...
ShapeBlue128 views
Igniting Next Level Productivity with AI-Infused Data Integration Workflows by Safe Software
Igniting Next Level Productivity with AI-Infused Data Integration Workflows Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Safe Software373 views

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