Top Banner
Yohan Beschi JAVA Expert
126

Java 8 - Nuts and Bold - SFEIR Benelux

Jul 16, 2015

Download

Technology

yohanbeschi
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Java 8 - Nuts and Bold - SFEIR Benelux

Yohan BeschiJAVA Expert

Page 2: Java 8 - Nuts and Bold - SFEIR Benelux

I II III

Page 3: Java 8 - Nuts and Bold - SFEIR Benelux

1

Page 4: Java 8 - Nuts and Bold - SFEIR Benelux

Comparator<Person> comparator = new Comparator<Person>() {

@Override

public int compare(Person o1, Person o2) {

return o1.firstname.compareTo(o2.firstname);

}

};

Page 5: Java 8 - Nuts and Bold - SFEIR Benelux

Comparator<Person> comparator =

(Person o1, Person o2)

-> o1.firstname.compareTo(o2.firstname);

Page 6: Java 8 - Nuts and Bold - SFEIR Benelux

Comparator<Person> comparator1 =

(o1, o2) -> o1.firstname.compareTo(o2.firstname);

Page 7: Java 8 - Nuts and Bold - SFEIR Benelux

Comparator<Person> comparator1 =

(o1, o2) -> {

return o1.firstname.compareTo(o2.firstname);

};

Page 8: Java 8 - Nuts and Bold - SFEIR Benelux

Comparator<Person> comparator1 =

(o1, o2) -> throw new Exception("Something went wrong");

Page 9: Java 8 - Nuts and Bold - SFEIR Benelux

Comparator<Person> comparator1 =

(o1, o2) -> throw new Exception("Something went wrong");

THE CONTENT OF THE LAMBDA MUST MATCH THE SIGNATURE OF THE METHOD IMPLEMENTED

Page 10: Java 8 - Nuts and Bold - SFEIR Benelux

Comparator<Person> comparator1 =

(o1, o2) -> throw new RuntimeException("Something went wrong");

RUNTIME EXCEPTION - THIS WILL COMPILE

Page 11: Java 8 - Nuts and Bold - SFEIR Benelux

2

Page 12: Java 8 - Nuts and Bold - SFEIR Benelux

@FunctionalInterface

public interface Compare<T> {

int compare(T o1, T o2);

boolean equals(Object obj);

}

Page 13: Java 8 - Nuts and Bold - SFEIR Benelux

public interface NotAFunctionalInterface {

int doSomething();

Object clone(); // Not public

}

Page 14: Java 8 - Nuts and Bold - SFEIR Benelux

public interface Function<T, R> {

R apply(T t);

}

Page 15: Java 8 - Nuts and Bold - SFEIR Benelux

Function<String, String> function = x -> x.toUpperCase();

Page 16: Java 8 - Nuts and Bold - SFEIR Benelux

Function<String, Function<String, String>> function

= x -> y -> y.toUpperCase();

Page 17: Java 8 - Nuts and Bold - SFEIR Benelux

public interface Supplier<T> {

T get();

}

Page 18: Java 8 - Nuts and Bold - SFEIR Benelux

Supplier<String> supplier = () -> "String1";

Page 19: Java 8 - Nuts and Bold - SFEIR Benelux

public interface Consumer<T> {

void accept(T t);

}

Page 20: Java 8 - Nuts and Bold - SFEIR Benelux

Consumer<String> consumer =

x -> System.out.println(x.toLowerCase());

Page 21: Java 8 - Nuts and Bold - SFEIR Benelux

public interface Predicate<T> {

boolean test(T t);

}

Page 22: Java 8 - Nuts and Bold - SFEIR Benelux

Predicate<Double> predicate = x -> x > 10.5;

Page 23: Java 8 - Nuts and Bold - SFEIR Benelux

public interface IntConsumer {

void accept(int value);

}

Page 24: Java 8 - Nuts and Bold - SFEIR Benelux

IntConsumer consumer = x -> System.out.println(x);

Page 25: Java 8 - Nuts and Bold - SFEIR Benelux

public interface BiFunction<T, U, R> {

R apply(T t, U u);

}

Page 26: Java 8 - Nuts and Bold - SFEIR Benelux

BiFunction<BigDecimal> function =

(left, right) -> left.multiply(right);

Page 27: Java 8 - Nuts and Bold - SFEIR Benelux

public interface BinaryOperator<T> extends BiFunction<T,T,T> {

// inherits: R apply(T t, U u);

}

Page 28: Java 8 - Nuts and Bold - SFEIR Benelux

BiFunction<BigDecimal> function =

(left, right) -> left.multiply(right);

Page 29: Java 8 - Nuts and Bold - SFEIR Benelux

3

Page 30: Java 8 - Nuts and Bold - SFEIR Benelux

public interface Postfixable {

public final static int UNARY_MESSAGE_PRIORITY = 1;

public final static int BINARY_MESSAGE_PRIORITY = 2;

// ...

int getPriority();

public default boolean le(Postfixable other) {

return this.getPriority() <= other.getPriority();

}

}

Page 31: Java 8 - Nuts and Bold - SFEIR Benelux

public interface Formula {

double calculate(int a);

default double sqrt(int a) {

return Math.sqrt(positive(a));

}

}

Formula formula = (a) -> sqrt( a * 100);

Page 32: Java 8 - Nuts and Bold - SFEIR Benelux

public interface Formula {

double calculate(int a);

default double sqrt(int a) {

return Math.sqrt(positive(a));

}

}

Formula formula = (a) -> sqrt( a * 100);

DOES NOT COMPILE

Page 33: Java 8 - Nuts and Bold - SFEIR Benelux

public static interface MyInterface1 {

default void foo(){

System.out.println("hello");

}

}

public static interface MyInterface2 {

default void foo(){

System.out.println("bye");

}

}

Page 34: Java 8 - Nuts and Bold - SFEIR Benelux

public static class MyClass implements MyInterface1, MyInterface2 {

// ...

}

Page 35: Java 8 - Nuts and Bold - SFEIR Benelux

public static class MyClass implements MyInterface1, MyInterface2 {

// ...

} DOES NOT COMPILE

Page 36: Java 8 - Nuts and Bold - SFEIR Benelux

public static abstract class MyClass

implements MyInterface1, MyInterface2 {

public abstract foo();

}

UN-IMPLEMENTING THE DEFAULT METHOD SOLVES THE PROBLEM

Page 37: Java 8 - Nuts and Bold - SFEIR Benelux

public static class MyClass implements MyInterface1, MyInterface2 {

public void foo() {

MyInterface1.super.foo();

MyInterface2.super.foo();

}

}

Page 38: Java 8 - Nuts and Bold - SFEIR Benelux

public static class MyClass1 implements MyInterface1 {

public void foo(){

System.out.println("bonjour");

}

}

public static class MyClass2 extends MyClass1 implements MyInterface2 {

}

Page 39: Java 8 - Nuts and Bold - SFEIR Benelux

public static class MyClass1 implements MyInterface1 {

public void foo(){

System.out.println("bonjour");

}

}

public static class MyClass2 extends MyClass1 implements MyInterface2 {

}

IN CASE OF AMBIGUITY A CLASS TAKES PRECEDENCE

Page 40: Java 8 - Nuts and Bold - SFEIR Benelux

4

Page 41: Java 8 - Nuts and Bold - SFEIR Benelux

public class Car {

public static Car create(final Supplier<Car> supplier) {

return supplier.get();

}

public static void collide(final Car car) {

System.out.println("Collided " + car.toString());

}

public void repair() {

System.out.println("Repaired " + this.toString());

}

public void follow(final Car another) {

System.out.println("Following the " + another.toString());

}

}

Page 42: Java 8 - Nuts and Bold - SFEIR Benelux

final Car car = Car.create(Car::new);

final List<Car> cars = Arrays.asList(car);

Page 43: Java 8 - Nuts and Bold - SFEIR Benelux

final Car car = Car.create(Car::new);

final List<Car> cars = Arrays.asList(car);

cars.forEach(Car::collide);

Page 44: Java 8 - Nuts and Bold - SFEIR Benelux

final Car car = Car.create(Car::new);

final List<Car> cars = Arrays.asList(car);

cars.forEach(Car::repair);

Page 45: Java 8 - Nuts and Bold - SFEIR Benelux

final Car car = Car.create(Car::new);

final List<Car> cars = Arrays.asList(car);

final Car police = Car.create(Car::new);

cars.forEach(police::follow);

Page 46: Java 8 - Nuts and Bold - SFEIR Benelux

public static UtfToCodePoint findUtfToCodePoint(final Charset charset) {

switch (charset) {

case UTF8:

case UTF8BOM:

return Converter::utf8ToCodePoint;

case UTF16BE:

return Converter::utf16beToCodePoint;

case UTF16LE:

return Converter::utf16leToCodePoint;

case UTF32BE:

return Converter::utf32beToCodePoint;

case UTF32LE:

return Converter::utf32leToCodePoint;

default:

throw new UnicodeException("Unknown charset!");

}

}

Page 47: Java 8 - Nuts and Bold - SFEIR Benelux

public class Person {

final private String firstName;

final private String lastName;

public Person() {}

public Person(String firstName, String lastName) {

this.firstName = firstName;

this.lastName = lastName;

}

}

public interface PersonFactory {

Person create(String firstName, String lastName);

}

Page 48: Java 8 - Nuts and Bold - SFEIR Benelux

PersonFactory<Person> personFactory = Person::new;

Person person = personFactory.create("Peter", "Parker");

Page 49: Java 8 - Nuts and Bold - SFEIR Benelux

5

Page 50: Java 8 - Nuts and Bold - SFEIR Benelux

Predicate<String> predicate = (s) -> s.length() > 0;

predicate.test("foo"); // true

predicate.negate().test("foo"); // false

Predicate<String> nonNull = Objects::nonNull;

Predicate<String> isNull = Objects::isNull;

Predicate<String> isEmpty = String::isEmpty;

Predicate<String> isNotEmpty = isEmpty.negate();

Page 51: Java 8 - Nuts and Bold - SFEIR Benelux

Function<String, Integer> toInteger = Integer::valueOf;

Function<String, String> backToString = toInteger.andThen(String::valueOf);

backToString.apply("123"); // "123"

Page 52: Java 8 - Nuts and Bold - SFEIR Benelux

Supplier<Person> personSupplier = Person::new;

personSupplier.get(); // new Person

Page 53: Java 8 - Nuts and Bold - SFEIR Benelux

Consumer<Person> greeter = p -> System.out.println("Hello, " + p.firstName);

greeter.accept(new Person("Luke", "Skywalker"));

Page 54: Java 8 - Nuts and Bold - SFEIR Benelux

6

Page 55: Java 8 - Nuts and Bold - SFEIR Benelux

Optional<String> optional = Optional.of("foo");

optional.isPresent(); // true

optional.get(); // "foo"

optional.orElse("fallback"); // "foo"

optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "f"

Page 56: Java 8 - Nuts and Bold - SFEIR Benelux

Optional<String> fullName = Optional.ofNullable(null);

System.out.println("Full Name is set? " + fullName.isPresent());

// Full Name is set? false

System.out.println("Full Name: " + fullName.orElseGet(() -> "[none]"));

// Full Name: [none]

System.out.println(fullName.map(s -> "Hey " + s + "!").orElse("Hey Stranger!"));

// Hey Stranger!

Page 57: Java 8 - Nuts and Bold - SFEIR Benelux

Optional<String> firstName = Optional.of("Tom");

System.out.println("First Name is set? " + firstName.isPresent());

// Full Name is set? true

System.out.println("First Name: " + firstName.orElseGet(() -> "[none]"));

// Full Name: Tom

System.out.println(firstName.map(s -> "Hey " + s + "!").orElse("Hey Stranger!"));

// Hey Tom!

Page 58: Java 8 - Nuts and Bold - SFEIR Benelux

7

Page 59: Java 8 - Nuts and Bold - SFEIR Benelux
Page 60: Java 8 - Nuts and Bold - SFEIR Benelux

public class Collections {

public static <T> void copy(List<? super T> dest, List<? extends T> src) {

for (int i = 0; i < src.size(); i++)

dest.set(i,src.get(i));

}

}

List<A> as = new ArrayList<>();

List<B> bs = new ArrayList<>();

List<C> cs = new ArrayList<>();

Collections.copy(List<A>, List<B>);

Collections.copy(List<A>, List<A>);

Collections.copy(List<A>, List<C>);

Collections.copy(List<B>, List<B>);

Collections.copy(List<B>, List<A>); // KO

Collections.copy(List<B>, List<C>);

Collections.copy(List<C>, List<B>); // KO

Collections.copy(List<C>, List<A>); // KO

Collections.copy(List<C>, List<C>);

public class A {

}

public class B extends A {

}

public class C extends B {

}

Page 61: Java 8 - Nuts and Bold - SFEIR Benelux

void forEach(Consumer<? super T> action)

List<Double> temperature = Arrays.asList(20.0, 22.0, 22.5);

temperature.forEach(System.out::println);

Page 62: Java 8 - Nuts and Bold - SFEIR Benelux

void sort(Comparator<? super E> c)

List<Double> temperature = Arrays.asList(20.0, 22.0, 22.5);

temperature.sort((a, b) -> a > b ? -1 : 1);

Page 63: Java 8 - Nuts and Bold - SFEIR Benelux

boolean removeIf(Predicate<? super E> filter)

List<Double> temperature = Arrays.asList(20.0, 22.0, 22.5);

temperature.removeIf(s -> s > 22);

Page 64: Java 8 - Nuts and Bold - SFEIR Benelux

void replaceAll(UnaryOperator<E> operator)

List<Double> temperature = Arrays.asList(20.0, 22.0, 22.5);

temperature.replaceAll(s -> Math.pow(s, 0.5));

Page 65: Java 8 - Nuts and Bold - SFEIR Benelux

void forEach(BiConsumer<? super K, ? super V> action)

Map<String , Integer> authorBooks = new HashMap<String , Integer>();

authorBooks.put("Robert Ludlum", 27);

authorBooks.put("Clive Cussler", 50);

authorBooks.put("Tom Clancy", 17);

authorBooks.forEach((a, b) -> System.out.println(a + " wrote " + b + " books"));

Page 66: Java 8 - Nuts and Bold - SFEIR Benelux

V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

Map<String , Integer> authorBooks = new HashMap<String , Integer>();

authorBooks.put("Robert Ludlum", 27);

authorBooks.put("Clive Cussler", 50);

authorBooks.put("Tom Clancy", 17);

authorBooks.compute("Clive Cussler", (a, b) -> b + 1);

// If the compute function returns null then the entry for that key is removed

// from the map. If the key is not present then a new entry is added.

Page 67: Java 8 - Nuts and Bold - SFEIR Benelux

V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)

Map<String , Integer> authorBooks = new HashMap<String , Integer>();

authorBooks.put("Robert Ludlum", 27);

authorBooks.put("Clive Cussler", 50);

authorBooks.put("Tom Clancy", 17);

authorBooks.computeIfAbsent("Agatha Christie", b -> b.length());

// The entry is added only if the computed value is not null.

Page 68: Java 8 - Nuts and Bold - SFEIR Benelux

V computeIfPresent(K key,

BiFunction<? super K, ? super V, ? extends V> remappingFunction)

Map<String , Integer> authorBooks = new HashMap<String , Integer>();

authorBooks.put("Robert Ludlum", 27);

authorBooks.put("Clive Cussler", 50);

authorBooks.put("Tom Clancy", 17);

authorBooks.computeIfPresent("Tom Clancy", (a, b) -> b + 1);

// Note that this function also removes an element if the new value computed from

// the passed lambda expression is null.

Page 69: Java 8 - Nuts and Bold - SFEIR Benelux

V getOrDefault(Object key, V defaultValue)

Map<String , Integer> authorBooks = new HashMap<String , Integer>();

authorBooks.put("Robert Ludlum", 27);

authorBooks.put("Clive Cussler", 50);

authorBooks.put("Tom Clancy", 17);

authorBooks.getOrDefault("AuthorA", 0)

Page 70: Java 8 - Nuts and Bold - SFEIR Benelux

V merge(K key, V value,

BiFunction<? super V, ? super V, ? extends V> remappingFunction)

Map<String , Integer> authorBooks = new HashMap<String , Integer>();

authorBooks.put("Robert Ludlum", 27);

authorBooks.put("Clive Cussler", 50);

authorBooks.put("Tom Clancy", 17);

authorBooks.merge("AuthorB", 1, (a, b) -> a + b);

System.out.println(authorBooks.get("AuthorB")); // 1

authorBooks.merge("AuthorB", 1, (a, b) -> a + b);

System.out.println(authorBooks.get("AuthorB")); // 2

Page 71: Java 8 - Nuts and Bold - SFEIR Benelux

V putIfAbsent(K key, V value)

Map<String , Integer> authorBooks = new HashMap<String , Integer>();

authorBooks.put("Robert Ludlum", 27);

authorBooks.put("Clive Cussler", 50);

authorBooks.put("Tom Clancy", 17);

System.out.println(authorBooks.putIfAbsent("AuthorC", 2)); // null

System.out.println(authorBooks.putIfAbsent("AuthorC", 2)); // 2

Page 72: Java 8 - Nuts and Bold - SFEIR Benelux

boolean remove(Object key, Object value)

V replace(K key, V newValue)

boolean replace(K key, V oldValue, V newValue)

void replaceAll (BiFunction<? super K, ? super V, ? extends V> function)

Page 73: Java 8 - Nuts and Bold - SFEIR Benelux

8

Page 74: Java 8 - Nuts and Bold - SFEIR Benelux

Comparator<Person> comparator =

(p1, p2) -> p1.firstname.compareTo(p2.firstname);

Page 75: Java 8 - Nuts and Bold - SFEIR Benelux

Comparator<Person> comparator = Comparator.comparing(p -> p.lastname)

Page 76: Java 8 - Nuts and Bold - SFEIR Benelux

Comparator<Person> comparator = Comparator.comparing(Person::getLastname);

Page 77: Java 8 - Nuts and Bold - SFEIR Benelux

Comparator<Person> comparator = (p1, p2) -> {

int r = p1.lastname.compareTo(p2.lastname);

if (r != 0)

return r;

return p1.firstname.compareTo(p2.firstname);

};

Page 78: Java 8 - Nuts and Bold - SFEIR Benelux

Comparator<Person> comparator4 = Comparator

.comparing(Person::getLastname)

.thenComparing(Person::getFirstname);

Page 79: Java 8 - Nuts and Bold - SFEIR Benelux

Comparator<Person> comparator = Comparator

.comparing(Person::getLastname)

.reverse()

.thenComparing(Person::getFirstname);

Page 80: Java 8 - Nuts and Bold - SFEIR Benelux

9

Page 81: Java 8 - Nuts and Bold - SFEIR Benelux
Page 82: Java 8 - Nuts and Bold - SFEIR Benelux
Page 83: Java 8 - Nuts and Bold - SFEIR Benelux
Page 84: Java 8 - Nuts and Bold - SFEIR Benelux
Page 85: Java 8 - Nuts and Bold - SFEIR Benelux
Page 86: Java 8 - Nuts and Bold - SFEIR Benelux
Page 87: Java 8 - Nuts and Bold - SFEIR Benelux
Page 88: Java 8 - Nuts and Bold - SFEIR Benelux
Page 89: Java 8 - Nuts and Bold - SFEIR Benelux
Page 90: Java 8 - Nuts and Bold - SFEIR Benelux
Page 91: Java 8 - Nuts and Bold - SFEIR Benelux
Page 92: Java 8 - Nuts and Bold - SFEIR Benelux
Page 93: Java 8 - Nuts and Bold - SFEIR Benelux
Page 94: Java 8 - Nuts and Bold - SFEIR Benelux

// The result won't be always the same

Set<Integer> seen = Collections.synchronizedSet(new HashSet<>());

stream.parallel().map(e -> {

if (seen.add(e)) return 0; else return e;

}

);

Page 95: Java 8 - Nuts and Bold - SFEIR Benelux

// with a stateless lambda expression the results would

always be the same.

IntStream.range(0,5).parallel().map(x -> x * 2).toArray()

// use reduction instead of mutable accumulators

Page 96: Java 8 - Nuts and Bold - SFEIR Benelux
Page 97: Java 8 - Nuts and Bold - SFEIR Benelux

int sum = numbers.stream().reduce(0, Integer::sum);

Page 98: Java 8 - Nuts and Bold - SFEIR Benelux

int sumOfWeights = widgets.stream()

.reduce(0,

(sum, b) -> sum + b.getWeight())

Integer::sum);

Page 99: Java 8 - Nuts and Bold - SFEIR Benelux
Page 100: Java 8 - Nuts and Bold - SFEIR Benelux

http://gotocon.com/dl/goto-amsterdam-2014/slides/PaulSandoz_PerchanceToStreamWithJava8.pdf

Source Decomposibility Characteristics

ArrayList (and arrays) Excellent SIZED, ORDERED

LinkedList Poor SIZED, ORDERED

HashSet Good SIZED, DISTINCT

TreeSet Good SIZED, DISTINCT, SORTED, ORDERED

IntStream.range() Excellent SIZED, DISTINCT, SORTED, ORDERED

Stream.iterate() Poor ORDERED

BufferedReader.lines() Poor ORDERED

SplittableRandom.ints() Excellent

Page 101: Java 8 - Nuts and Bold - SFEIR Benelux

String<String> stream = Arrays.asList("a", "b", "c").stream();

String<String> stream = Stream.of("a", "b", "c")

Stream<String> stream = Files.lines(Paths.get(uri));

Page 102: Java 8 - Nuts and Bold - SFEIR Benelux

10

Page 103: Java 8 - Nuts and Bold - SFEIR Benelux
Page 104: Java 8 - Nuts and Bold - SFEIR Benelux

String<String> stream = Arrays.asList("a", "b", "c").stream();

String<String> stream = Stream.of("a", "b", "c")

Stream<String> stream = Files.lines(Paths.get(uri));

collection.stream();

collection.parellelStream();

Page 105: Java 8 - Nuts and Bold - SFEIR Benelux

static <T> Stream<T> generate(Supplier<T> s)

static <T> Stream<T> iterate(T seed, UnaryOperator<T> f)

static <T> Stream<T> concat(Stream<? extends T> a,

Stream<? extends T> b)

static <T> Stream<T> of(T... values)

static <T> Stream<T> empty()

Page 106: Java 8 - Nuts and Bold - SFEIR Benelux

Stream<T> limit(long maxSize)

Stream<T> distinct()

Stream<T> filter(Predicate<? super T> predicate)

Page 107: Java 8 - Nuts and Bold - SFEIR Benelux

<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)

DoubleStream flatMapToDouble(Function<? super T,? extends DoubleStream> mapper)

IntStream flatMapToInt(Function<? super T,? extends IntStream> mapper)

LongStream flatMapToLong(Function<? super T,? extends LongStream> mapper)

Page 108: Java 8 - Nuts and Bold - SFEIR Benelux

<R> Stream<R> map(Function<? super T,? extends R> mapper)

DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper)

IntStream mapToInt(ToIntFunction<? super T> mapper)

LongStream mapToLong(ToLongFunction<? super T> mapper)

Page 109: Java 8 - Nuts and Bold - SFEIR Benelux

long count()

boolean allMatch(Predicate<? super T> predicate)

boolean anyMatch(Predicate<? super T> predicate)

boolean noneMatch(Predicate<? super T> predicate)

Optional<T> findAny()

Optional<T> findFirst()

Optional<T> max(Comparator<? super T> comparator)

Optional<T> min(Comparator<? super T> comparator)

Page 110: Java 8 - Nuts and Bold - SFEIR Benelux

Optional<T> reduce(BinaryOperator<T> accumulator)

T reduce(T identity, BinaryOperator<T> accumulator)

<U> U reduce(U identity,

BiFunction<U,? super T,U> accumulator,

BinaryOperator<U> combiner)

Page 111: Java 8 - Nuts and Bold - SFEIR Benelux

Object[] toArray()

<A> A[] toArray(IntFunction<A[]> generator)

Page 112: Java 8 - Nuts and Bold - SFEIR Benelux

void forEach(Consumer<? super T> action)

void forEachOrdered(Consumer<? super T> action)

Page 113: Java 8 - Nuts and Bold - SFEIR Benelux

<R,A> R collect(Collector<? super T,A,R> collector)

<R> R collect(Supplier<R> supplier,

BiConsumer<R,? super T> accumulator,

BiConsumer<R,R> combiner)

Page 114: Java 8 - Nuts and Bold - SFEIR Benelux
Page 115: Java 8 - Nuts and Bold - SFEIR Benelux

public void closure() {

List<Supplier<Integer>> list = new ArrayList<>();

for (int i = 1; i <= 5; i++) {

list.add(() -> i);

}

}

Page 116: Java 8 - Nuts and Bold - SFEIR Benelux

public void closure() {

List<Supplier<Integer>> list = new ArrayList<>();

for (int i = 1; i <= 5; i++) {

list.add(() -> i);

}

}

DOES NOT COMPILEThe value of « i » changes along the way

Page 117: Java 8 - Nuts and Bold - SFEIR Benelux

public void closure() {

List<Supplier<Integer>> list = new ArrayList<>();

for (int i = 1; i <= 5; i++) {

final int j = i;

list.add(() -> j);

}

list.forEach((e) -> System.out.print(e.get())); // 12345

}

COMPILEA new « j » variable is created at each iteration

Page 118: Java 8 - Nuts and Bold - SFEIR Benelux

public void closure() {

List<Supplier<Integer>> list = new ArrayList<>();

for (int i = 1; i <= 5; i++) {

final int j = i;

list.add(() -> j);

}

list.forEach((e) -> System.out.print(e.get())); // 12345

}

The « final » keyword is not mandatory as the value of « j » is set once and for allIn this example « j » IS EFFECTIVELY FINAL

Page 119: Java 8 - Nuts and Bold - SFEIR Benelux

public void closure() {

List<Supplier<Integer>> list =

IntStream.range(1, 6)

.mapToObj((i) -> (Supplier<Integer>) () -> i)

.collect(Collectors.toList());

list.forEach((e) -> System.out.print(e.get())); // 12345

}

Page 120: Java 8 - Nuts and Bold - SFEIR Benelux

public class Closure {

private int index = 1;

public void closure() {

List<Supplier<Integer>> list =

IntStream.range(-5, 0)

.mapToObj((i) -> (Supplier<Integer>) () -> index++)

.collect(Collectors.toList());

list.forEach((e) -> System.out.print(e.get())); // 12345

}

}

Page 121: Java 8 - Nuts and Bold - SFEIR Benelux
Page 122: Java 8 - Nuts and Bold - SFEIR Benelux
Page 123: Java 8 - Nuts and Bold - SFEIR Benelux

http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html

Page 124: Java 8 - Nuts and Bold - SFEIR Benelux

11

Page 125: Java 8 - Nuts and Bold - SFEIR Benelux

http://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.htmlhttp://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html

Page 126: Java 8 - Nuts and Bold - SFEIR Benelux