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

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
Bartosz Kosarzycki
 

What's hot (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
 

Viewers also liked

Viewers also liked (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
 

Similar to Intro to Java 8 Closures (Dainius Mezanskas)

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
Mario Fusco
 

Similar to 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
 

More from Kaunas Java User Group

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 Java User Group
 

More from 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)
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

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