Java 8
Intro to Closures (Laλλbdas)
Kaunas JUG
Dainius Mežanskas · kaunas.jug@gmail.com · http://plus.google.com/+KaunasJU...
Dainius Mežanskas
● 16 years of Java
● Java SE/EE
● e-Learning · Insurance · Telecommunications ·
e-Commerce
● KTU DMC · E...
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();...
Why Lambda in Java
● 1 line instead of 5
● Functional programming
● References to methods
● Conciser collections API
● Str...
Functional Interface
● Single Abstract Method Interfaces (SAM)
● java.lang.Runnable, java.awt.event.ActionListener, java.u...
@FunctionalInterface (1)
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
@FunctionalInterface (2)
@FunctionalInterface
public interface Builder {
public abstract void build();
public abstract Str...
@FunctionalInterface (3)
@FunctionalInterface
public interface Builder {
public abstract void build();
public abstract boo...
@FunctionalInterface (4)
@FunctionalInterface
public interface Builder {
public abstract void build();
public default bool...
@FunctionalInterface (5)
@FunctionalInterface
public interface Builder {
public abstract void build();
public abstract Str...
Lambda Syntax
● Argument List - zero or more
● Body - a single expression or a statement block
Argument List Arrow Token B...
Lambda Examples
(int x, int y) -> x + y
() -> 42
a -> { return a * a; }
(a) -> a * a
(String s) -> { System.out.println(s)...
public class RunnableLambda {
public static void main(String[] args) {
Runnable runAnonymous = new Runnable() {
public voi...
List<String> vegetables =
Arrays.asList( "Carrot", "Watercress", "Dill", "Pea" );
Collections.sort( vegetables,
(String s1...
CustomInterface
Lambda
public static void main(String[] args) {
Artist artist = new Artist();
artist.perform(
() -> System...
java.util.function
● Consumer<T> / void accept(T t);
● Function<T, R> / R apply(T t);
● blahOperator / ~vary~
● Predicate<...
Lambda.this · Object = · final
● () -> { print(this); } // this == outer object
● Object n = () -> { print(“Wow!”)}; // co...
Default Methods
● Aka. Virtual Extension Methods or Defender Methods
● Inspired by Limitations designing Java 8 Collection...
List.forEach()
public interface Iterable<T> {
.....
default void forEach(Consumer action) {
for (T t : this) {
action.acce...
Collections API additions
● Iterable.forEach(Consumer)
● Iterator.forEachRemaining(Consumer)
● Collection.removeIf(Predica...
Method References
Method
String::valueOf
Object::toString
x::toString
ArrayList::new
Lambda
x -> String.valueOf(x)
x -> x....
Streams
● Filter-Map-Reduce
● Infinite and stateful
● Sequential or parallel
● One or more intermediate operations
filter,...
Happy Birthday Java 8!
Upcoming SlideShare
Loading in …5
×

Intro to Java 8 Closures (Dainius Mezanskas)

3,292 views
3,006 views

Published on

Published in: Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,292
On SlideShare
0
From Embeds
0
Number of Embeds
10
Actions
Shares
0
Downloads
53
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

Intro to Java 8 Closures (Dainius Mezanskas)

  1. 1. Java 8 Intro to Closures (Laλλbdas) Kaunas JUG Dainius Mežanskas · kaunas.jug@gmail.com · http://plus.google.com/+KaunasJUG { λ }
  2. 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
  3. 3. Presentation Source Code https://github.com/dainiusm/kaunasjug2lambdas.git
  4. 4. What is Lambda? (aka. Closure) ● Anonymous function in programming ● Provides a way to write closures
  5. 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. 6. Why Lambda in Java ● 1 line instead of 5 ● Functional programming ● References to methods ● Conciser collections API ● Streams · Filter/map/reduce ...
  7. 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. 8. @FunctionalInterface (1) @FunctionalInterface public interface Runnable { public abstract void run(); }
  9. 9. @FunctionalInterface (2) @FunctionalInterface public interface Builder { public abstract void build(); public abstract String toString(); }
  10. 10. @FunctionalInterface (3) @FunctionalInterface public interface Builder { public abstract void build(); public abstract boolean isTrusted(); }
  11. 11. @FunctionalInterface (4) @FunctionalInterface public interface Builder { public abstract void build(); public default boolean isTrusted() { return false; } }
  12. 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. 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. 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. 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. 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. 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. 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. 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. 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. 21. List.forEach() public interface Iterable<T> { ..... default void forEach(Consumer action) { for (T t : this) { action.accept(t); } } CollectionsBulkAndStream.java
  22. 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. 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. 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
  25. 25. Happy Birthday Java 8!

×