Intro to Java 8 Closures (Dainius Mezanskas)
-
Upload
kaunas-java-user-group -
Category
Technology
-
view
112 -
download
1
description
Transcript of Intro to Java 8 Closures (Dainius Mezanskas)
Java 8Intro to Closures (Laλλbdas)
Kaunas JUG
Dainius Mežanskas · [email protected] · 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 Codehttps://github.com/dainiusm/kaunasjug2lambdas.git
What is Lambda? (aka. Closure)
● Anonymous function in
programming
● Provides a way to write
closures
Closurefunction adder() { def x = 0;
function incrementX() { x = x + 1; return x; }
return incrementX;}
def y = adder(); // Ref to closurey(); // 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)
@FunctionalInterfacepublic interface Runnable { public abstract void run();}
@FunctionalInterface (2)
@FunctionalInterfacepublic interface Builder { public abstract void build(); public abstract String toString();}
@FunctionalInterface (3)
@FunctionalInterfacepublic interface Builder { public abstract void build(); public abstract boolean isTrusted();}
@FunctionalInterface (4)
@FunctionalInterfacepublic interface Builder { public abstract void build(); public default boolean isTrusted() { return false; }}
@FunctionalInterface (5)
@FunctionalInterfacepublic 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();
}}R
unna
ble
Lam
bda
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 );
Com
para
tor L
ambd
a
ComparatorLambda.java
Cus
tom
Inte
rfac
e La
mbd
apublic static void main(String[] args) {
Artist artist = new Artist();
artist.perform( () -> System.out.println("Hello, Lambda")
);}
@FunctionalInterfaceinterface 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.javaObjectLambda.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 operationsfilter, map, flatMap, peel, distinct, sorted, limit, and substream
● One final terminal operationforEach, toArray, reduce, collect, min, max, count, anyMatch, allMatch, noneMatch, findFirst, and findAny
Happy Birthday Java 8!