Intro to Java 8 Lambdas

25
Java 8 Intro to Closures (Laλλbdas) Kaunas JUG Dainius Mežanskas · [email protected] · http://plus.google.com/+KaunasJUG { λ }

Transcript of Intro to Java 8 Lambdas

Page 1: Intro to Java 8 Lambdas

Java 8Intro to Closures (Laλλbdas)

Kaunas JUG

Dainius Mežanskas · [email protected] · http://plus.google.com/+KaunasJUG

{ λ }

Page 2: Intro to Java 8 Lambdas

Dainius Mežanskas

● 16 years of Java

● Java SE/EE

● e-Learning · Insurance · Telecommunications ·

e-Commerce

● KTU DMC · Exigen Group · NoMagic Europe ·

Modnique Baltic

Page 3: Intro to Java 8 Lambdas

Presentation Source Codehttps://github.com/dainiusm/kaunasjug2lambdas.git

Page 4: Intro to Java 8 Lambdas

What is Lambda? (aka. Closure)

● Anonymous function in

programming

● Provides a way to write

closures

Page 5: Intro to Java 8 Lambdas

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)

Page 6: Intro to Java 8 Lambdas

Why Lambda in Java

● 1 line instead of 5

● Functional programming

● References to methods

● Conciser collections API

● Streams · Filter/map/reduce

...

Page 7: Intro to Java 8 Lambdas

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

Page 8: Intro to Java 8 Lambdas

@FunctionalInterface (1)

@FunctionalInterfacepublic interface Runnable { public abstract void run();}

Page 9: Intro to Java 8 Lambdas

@FunctionalInterface (2)

@FunctionalInterfacepublic interface Builder { public abstract void build(); public abstract String toString();}

Page 10: Intro to Java 8 Lambdas

@FunctionalInterface (3)

@FunctionalInterfacepublic interface Builder { public abstract void build(); public abstract boolean isTrusted();}

Page 11: Intro to Java 8 Lambdas

@FunctionalInterface (4)

@FunctionalInterfacepublic interface Builder { public abstract void build(); public default boolean isTrusted() { return false; }}

Page 12: Intro to Java 8 Lambdas

@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

Page 13: Intro to Java 8 Lambdas

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

Page 14: Intro to Java 8 Lambdas

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);

Page 15: Intro to Java 8 Lambdas

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

Page 16: Intro to Java 8 Lambdas

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

Page 17: Intro to Java 8 Lambdas

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

Page 18: Intro to Java 8 Lambdas

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

Page 19: Intro to Java 8 Lambdas

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

Page 20: Intro to Java 8 Lambdas

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

Page 21: Intro to Java 8 Lambdas

List.forEach()public interface Iterable<T> {.....default void forEach(Consumer action) { for (T t : this) { action.accept(t); }}

CollectionsBulkAndStream.java

Page 22: Intro to Java 8 Lambdas

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)

Page 23: Intro to Java 8 Lambdas

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

Page 24: Intro to Java 8 Lambdas

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

Page 25: Intro to Java 8 Lambdas

Happy Birthday Java 8!