SlideShare une entreprise Scribd logo
1  sur  126
Télécharger pour lire hors ligne
Yohan Beschi
JAVA Expert
I II III
1
Comparator<Person> comparator = new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.firstname.compareTo(o2.firstname);
}
};
Comparator<Person> comparator =
(Person o1, Person o2)
-> o1.firstname.compareTo(o2.firstname);
Comparator<Person> comparator1 =
(o1, o2) -> o1.firstname.compareTo(o2.firstname);
Comparator<Person> comparator1 =
(o1, o2) -> {
return o1.firstname.compareTo(o2.firstname);
};
Comparator<Person> comparator1 =
(o1, o2) -> throw new Exception("Something went wrong");
Comparator<Person> comparator1 =
(o1, o2) -> throw new Exception("Something went wrong");
THE CONTENT OF THE LAMBDA MUST MATCH THE SIGNATURE
OF THE METHOD IMPLEMENTED
Comparator<Person> comparator1 =
(o1, o2) -> throw new RuntimeException("Something went wrong");
RUNTIME EXCEPTION - THIS WILL COMPILE
2
@FunctionalInterface
public interface Compare<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
}
public interface NotAFunctionalInterface {
int doSomething();
Object clone(); // Not public
}
public interface Function<T, R> {
R apply(T t);
}
Function<String, String> function = x -> x.toUpperCase();
Function<String, Function<String, String>> function
= x -> y -> y.toUpperCase();
public interface Supplier<T> {
T get();
}
Supplier<String> supplier = () -> "String1";
public interface Consumer<T> {
void accept(T t);
}
Consumer<String> consumer =
x -> System.out.println(x.toLowerCase());
public interface Predicate<T> {
boolean test(T t);
}
Predicate<Double> predicate = x -> x > 10.5;
public interface IntConsumer {
void accept(int value);
}
IntConsumer consumer = x -> System.out.println(x);
public interface BiFunction<T, U, R> {
R apply(T t, U u);
}
BiFunction<BigDecimal> function =
(left, right) -> left.multiply(right);
public interface BinaryOperator<T> extends BiFunction<T,T,T> {
// inherits: R apply(T t, U u);
}
BiFunction<BigDecimal> function =
(left, right) -> left.multiply(right);
3
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();
}
}
public interface Formula {
double calculate(int a);
default double sqrt(int a) {
return Math.sqrt(positive(a));
}
}
Formula formula = (a) -> sqrt( a * 100);
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
public static interface MyInterface1 {
default void foo(){
System.out.println("hello");
}
}
public static interface MyInterface2 {
default void foo(){
System.out.println("bye");
}
}
public static class MyClass implements MyInterface1, MyInterface2 {
// ...
}
public static class MyClass implements MyInterface1, MyInterface2 {
// ...
} DOES NOT COMPILE
public static abstract class MyClass
implements MyInterface1, MyInterface2 {
public abstract foo();
}
UN-IMPLEMENTING THE DEFAULT METHOD SOLVES THE PROBLEM
public static class MyClass implements MyInterface1, MyInterface2 {
public void foo() {
MyInterface1.super.foo();
MyInterface2.super.foo();
}
}
public static class MyClass1 implements MyInterface1 {
public void foo(){
System.out.println("bonjour");
}
}
public static class MyClass2 extends MyClass1 implements MyInterface2 {
}
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
4
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());
}
}
final Car car = Car.create(Car::new);
final List<Car> cars = Arrays.asList(car);
final Car car = Car.create(Car::new);
final List<Car> cars = Arrays.asList(car);
cars.forEach(Car::collide);
final Car car = Car.create(Car::new);
final List<Car> cars = Arrays.asList(car);
cars.forEach(Car::repair);
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);
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!");
}
}
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);
}
PersonFactory<Person> personFactory = Person::new;
Person person = personFactory.create("Peter", "Parker");
5
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();
Function<String, Integer> toInteger = Integer::valueOf;
Function<String, String> backToString = toInteger.andThen(String::valueOf);
backToString.apply("123"); // "123"
Supplier<Person> personSupplier = Person::new;
personSupplier.get(); // new Person
Consumer<Person> greeter = p -> System.out.println("Hello, " + p.firstName);
greeter.accept(new Person("Luke", "Skywalker"));
6
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"
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!
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!
7
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 {
}
void forEach(Consumer<? super T> action)
List<Double> temperature = Arrays.asList(20.0, 22.0, 22.5);
temperature.forEach(System.out::println);
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);
boolean removeIf(Predicate<? super E> filter)
List<Double> temperature = Arrays.asList(20.0, 22.0, 22.5);
temperature.removeIf(s -> s > 22);
void replaceAll(UnaryOperator<E> operator)
List<Double> temperature = Arrays.asList(20.0, 22.0, 22.5);
temperature.replaceAll(s -> Math.pow(s, 0.5));
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"));
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.
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.
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.
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)
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
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
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)
8
Comparator<Person> comparator =
(p1, p2) -> p1.firstname.compareTo(p2.firstname);
Comparator<Person> comparator = Comparator.comparing(p -> p.lastname)
Comparator<Person> comparator = Comparator.comparing(Person::getLastname);
Comparator<Person> comparator = (p1, p2) -> {
int r = p1.lastname.compareTo(p2.lastname);
if (r != 0)
return r;
return p1.firstname.compareTo(p2.firstname);
};
Comparator<Person> comparator4 = Comparator
.comparing(Person::getLastname)
.thenComparing(Person::getFirstname);
Comparator<Person> comparator = Comparator
.comparing(Person::getLastname)
.reverse()
.thenComparing(Person::getFirstname);
9
// 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;
}
);
// 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
int sum = numbers.stream().reduce(0, Integer::sum);
int sumOfWeights = widgets.stream()
.reduce(0,
(sum, b) -> sum + b.getWeight())
Integer::sum);
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
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));
10
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();
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()
Stream<T> limit(long maxSize)
Stream<T> distinct()
Stream<T> filter(Predicate<? super T> predicate)
<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)
<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)
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)
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)
Object[] toArray()
<A> A[] toArray(IntFunction<A[]> generator)
void forEach(Consumer<? super T> action)
void forEachOrdered(Consumer<? super T> action)
<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)
public void closure() {
List<Supplier<Integer>> list = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
list.add(() -> i);
}
}
public void closure() {
List<Supplier<Integer>> list = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
list.add(() -> i);
}
}
DOES NOT COMPILE
The value of « i » changes along the way
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
}
COMPILE
A new « j » variable is created at each iteration
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 all
In this example « j » IS EFFECTIVELY FINAL
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
}
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
}
}
http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html
11
http://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
Java 8 - Nuts and Bold - SFEIR Benelux

Contenu connexe

Tendances

Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012Sandeep Joshi
 
Google guava - almost everything you need to know
Google guava - almost everything you need to knowGoogle guava - almost everything you need to know
Google guava - almost everything you need to knowTomasz Dziurko
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner codeMite Mitreski
 
The core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaThe core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaMite Mitreski
 
Works Applications Test - Chinmay Chauhan
Works Applications Test - Chinmay ChauhanWorks Applications Test - Chinmay Chauhan
Works Applications Test - Chinmay ChauhanChinmay Chauhan
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iiiNiraj Bharambe
 
The Ring programming language version 1.5.2 book - Part 26 of 181
The Ring programming language version 1.5.2 book - Part 26 of 181The Ring programming language version 1.5.2 book - Part 26 of 181
The Ring programming language version 1.5.2 book - Part 26 of 181Mahmoud Samir Fayed
 
Smarter Testing with Spock
Smarter Testing with SpockSmarter Testing with Spock
Smarter Testing with SpockDmitry Voloshko
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql JOYITAKUNDU1
 
Evolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and EffectiveEvolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and EffectiveNaresha K
 
The Ring programming language version 1.5.4 book - Part 79 of 185
The Ring programming language version 1.5.4 book - Part 79 of 185The Ring programming language version 1.5.4 book - Part 79 of 185
The Ring programming language version 1.5.4 book - Part 79 of 185Mahmoud Samir Fayed
 
The Ring programming language version 1.5.2 book - Part 76 of 181
The Ring programming language version 1.5.2 book - Part 76 of 181The Ring programming language version 1.5.2 book - Part 76 of 181
The Ring programming language version 1.5.2 book - Part 76 of 181Mahmoud Samir Fayed
 
The Ring programming language version 1.10 book - Part 17 of 212
The Ring programming language version 1.10 book - Part 17 of 212The Ring programming language version 1.10 book - Part 17 of 212
The Ring programming language version 1.10 book - Part 17 of 212Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180Mahmoud Samir Fayed
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2Technopark
 

Tendances (20)

Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
Google guava - almost everything you need to know
Google guava - almost everything you need to knowGoogle guava - almost everything you need to know
Google guava - almost everything you need to know
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
The core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaThe core libraries you always wanted - Google Guava
The core libraries you always wanted - Google Guava
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Specs2
Specs2Specs2
Specs2
 
Works Applications Test - Chinmay Chauhan
Works Applications Test - Chinmay ChauhanWorks Applications Test - Chinmay Chauhan
Works Applications Test - Chinmay Chauhan
 
java assignment
java assignmentjava assignment
java assignment
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
 
The Ring programming language version 1.5.2 book - Part 26 of 181
The Ring programming language version 1.5.2 book - Part 26 of 181The Ring programming language version 1.5.2 book - Part 26 of 181
The Ring programming language version 1.5.2 book - Part 26 of 181
 
Smarter Testing with Spock
Smarter Testing with SpockSmarter Testing with Spock
Smarter Testing with Spock
 
DCN Practical
DCN PracticalDCN Practical
DCN Practical
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql
 
Evolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and EffectiveEvolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and Effective
 
The Ring programming language version 1.5.4 book - Part 79 of 185
The Ring programming language version 1.5.4 book - Part 79 of 185The Ring programming language version 1.5.4 book - Part 79 of 185
The Ring programming language version 1.5.4 book - Part 79 of 185
 
The Ring programming language version 1.5.2 book - Part 76 of 181
The Ring programming language version 1.5.2 book - Part 76 of 181The Ring programming language version 1.5.2 book - Part 76 of 181
The Ring programming language version 1.5.2 book - Part 76 of 181
 
The Ring programming language version 1.10 book - Part 17 of 212
The Ring programming language version 1.10 book - Part 17 of 212The Ring programming language version 1.10 book - Part 17 of 212
The Ring programming language version 1.10 book - Part 17 of 212
 
The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2
 
Java practical
Java practicalJava practical
Java practical
 

Similaire à Java 8 - Nuts and Bold - SFEIR Benelux

Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oopLearningTech
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In JavaAndrei Solntsev
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Codemotion
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Baruch Sadogursky
 
Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mark Needham
 
JDD2015: Where Test Doubles can lead you... - Sebastian Malaca
JDD2015: Where Test Doubles can lead you...  - Sebastian Malaca JDD2015: Where Test Doubles can lead you...  - Sebastian Malaca
JDD2015: Where Test Doubles can lead you... - Sebastian Malaca PROIDEA
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wildJoe Morgan
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to SwiftGiordano Scalzo
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageDroidConTLV
 
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)Ontico
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguageSamir Chekkal
 
Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming languageSQLI
 

Similaire à Java 8 - Nuts and Bold - SFEIR Benelux (20)

Introduccion a Jasmin
Introduccion a JasminIntroduccion a Jasmin
Introduccion a Jasmin
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
 
Property-based testing
Property-based testingProperty-based testing
Property-based testing
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In Java
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
 
Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#
 
JDD2015: Where Test Doubles can lead you... - Sebastian Malaca
JDD2015: Where Test Doubles can lead you...  - Sebastian Malaca JDD2015: Where Test Doubles can lead you...  - Sebastian Malaca
JDD2015: Where Test Doubles can lead you... - Sebastian Malaca
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wild
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritage
 
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
 
Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming language
 
Unit testing concurrent code
Unit testing concurrent codeUnit testing concurrent code
Unit testing concurrent code
 

Plus de yohanbeschi

VoxxedDays LU 2016 - Thoughtworks Go - Continuous Deployment made easy and free
VoxxedDays LU 2016 - Thoughtworks Go - Continuous Deployment made easy and freeVoxxedDays LU 2016 - Thoughtworks Go - Continuous Deployment made easy and free
VoxxedDays LU 2016 - Thoughtworks Go - Continuous Deployment made easy and freeyohanbeschi
 
JVM Hardcore - Part 18 - Converting a logical expression into bytecode
JVM Hardcore - Part 18 - Converting a logical expression into bytecodeJVM Hardcore - Part 18 - Converting a logical expression into bytecode
JVM Hardcore - Part 18 - Converting a logical expression into bytecodeyohanbeschi
 
JVM Hardcore - Part 07 - Parsing (Productions stack states)
JVM Hardcore - Part 07 - Parsing (Productions stack states)JVM Hardcore - Part 07 - Parsing (Productions stack states)
JVM Hardcore - Part 07 - Parsing (Productions stack states)yohanbeschi
 
Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924yohanbeschi
 
JVM Hardcode - Part 01 - How Frames work
JVM Hardcode - Part 01 - How Frames workJVM Hardcode - Part 01 - How Frames work
JVM Hardcode - Part 01 - How Frames workyohanbeschi
 
Introduction to dart - So@t - 20130410
Introduction to dart - So@t - 20130410Introduction to dart - So@t - 20130410
Introduction to dart - So@t - 20130410yohanbeschi
 
Dart - web_ui & Programmatic components - Paris JUG - 20130409
Dart - web_ui & Programmatic components - Paris JUG - 20130409Dart - web_ui & Programmatic components - Paris JUG - 20130409
Dart - web_ui & Programmatic components - Paris JUG - 20130409yohanbeschi
 
Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013yohanbeschi
 
Introduction à dart
Introduction à dartIntroduction à dart
Introduction à dartyohanbeschi
 

Plus de yohanbeschi (9)

VoxxedDays LU 2016 - Thoughtworks Go - Continuous Deployment made easy and free
VoxxedDays LU 2016 - Thoughtworks Go - Continuous Deployment made easy and freeVoxxedDays LU 2016 - Thoughtworks Go - Continuous Deployment made easy and free
VoxxedDays LU 2016 - Thoughtworks Go - Continuous Deployment made easy and free
 
JVM Hardcore - Part 18 - Converting a logical expression into bytecode
JVM Hardcore - Part 18 - Converting a logical expression into bytecodeJVM Hardcore - Part 18 - Converting a logical expression into bytecode
JVM Hardcore - Part 18 - Converting a logical expression into bytecode
 
JVM Hardcore - Part 07 - Parsing (Productions stack states)
JVM Hardcore - Part 07 - Parsing (Productions stack states)JVM Hardcore - Part 07 - Parsing (Productions stack states)
JVM Hardcore - Part 07 - Parsing (Productions stack states)
 
Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924
 
JVM Hardcode - Part 01 - How Frames work
JVM Hardcode - Part 01 - How Frames workJVM Hardcode - Part 01 - How Frames work
JVM Hardcode - Part 01 - How Frames work
 
Introduction to dart - So@t - 20130410
Introduction to dart - So@t - 20130410Introduction to dart - So@t - 20130410
Introduction to dart - So@t - 20130410
 
Dart - web_ui & Programmatic components - Paris JUG - 20130409
Dart - web_ui & Programmatic components - Paris JUG - 20130409Dart - web_ui & Programmatic components - Paris JUG - 20130409
Dart - web_ui & Programmatic components - Paris JUG - 20130409
 
Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013
 
Introduction à dart
Introduction à dartIntroduction à dart
Introduction à dart
 

Dernier

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
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 organizationRadu Cotescu
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 

Dernier (20)

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 

Java 8 - Nuts and Bold - SFEIR Benelux

  • 3. 1
  • 4. Comparator<Person> comparator = new Comparator<Person>() { @Override public int compare(Person o1, Person o2) { return o1.firstname.compareTo(o2.firstname); } };
  • 5. Comparator<Person> comparator = (Person o1, Person o2) -> o1.firstname.compareTo(o2.firstname);
  • 6. Comparator<Person> comparator1 = (o1, o2) -> o1.firstname.compareTo(o2.firstname);
  • 7. Comparator<Person> comparator1 = (o1, o2) -> { return o1.firstname.compareTo(o2.firstname); };
  • 8. Comparator<Person> comparator1 = (o1, o2) -> throw new Exception("Something went wrong");
  • 9. Comparator<Person> comparator1 = (o1, o2) -> throw new Exception("Something went wrong"); THE CONTENT OF THE LAMBDA MUST MATCH THE SIGNATURE OF THE METHOD IMPLEMENTED
  • 10. Comparator<Person> comparator1 = (o1, o2) -> throw new RuntimeException("Something went wrong"); RUNTIME EXCEPTION - THIS WILL COMPILE
  • 11. 2
  • 12. @FunctionalInterface public interface Compare<T> { int compare(T o1, T o2); boolean equals(Object obj); }
  • 13. public interface NotAFunctionalInterface { int doSomething(); Object clone(); // Not public }
  • 14. public interface Function<T, R> { R apply(T t); }
  • 15. Function<String, String> function = x -> x.toUpperCase();
  • 16. Function<String, Function<String, String>> function = x -> y -> y.toUpperCase();
  • 18. Supplier<String> supplier = () -> "String1";
  • 19. public interface Consumer<T> { void accept(T t); }
  • 20. Consumer<String> consumer = x -> System.out.println(x.toLowerCase());
  • 21. public interface Predicate<T> { boolean test(T t); }
  • 23. public interface IntConsumer { void accept(int value); }
  • 24. IntConsumer consumer = x -> System.out.println(x);
  • 25. public interface BiFunction<T, U, R> { R apply(T t, U u); }
  • 26. BiFunction<BigDecimal> function = (left, right) -> left.multiply(right);
  • 27. public interface BinaryOperator<T> extends BiFunction<T,T,T> { // inherits: R apply(T t, U u); }
  • 28. BiFunction<BigDecimal> function = (left, right) -> left.multiply(right);
  • 29. 3
  • 30. 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(); } }
  • 31. public interface Formula { double calculate(int a); default double sqrt(int a) { return Math.sqrt(positive(a)); } } Formula formula = (a) -> sqrt( a * 100);
  • 32. 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
  • 33. public static interface MyInterface1 { default void foo(){ System.out.println("hello"); } } public static interface MyInterface2 { default void foo(){ System.out.println("bye"); } }
  • 34. public static class MyClass implements MyInterface1, MyInterface2 { // ... }
  • 35. public static class MyClass implements MyInterface1, MyInterface2 { // ... } DOES NOT COMPILE
  • 36. public static abstract class MyClass implements MyInterface1, MyInterface2 { public abstract foo(); } UN-IMPLEMENTING THE DEFAULT METHOD SOLVES THE PROBLEM
  • 37. public static class MyClass implements MyInterface1, MyInterface2 { public void foo() { MyInterface1.super.foo(); MyInterface2.super.foo(); } }
  • 38. public static class MyClass1 implements MyInterface1 { public void foo(){ System.out.println("bonjour"); } } public static class MyClass2 extends MyClass1 implements MyInterface2 { }
  • 39. 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
  • 40. 4
  • 41. 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()); } }
  • 42. final Car car = Car.create(Car::new); final List<Car> cars = Arrays.asList(car);
  • 43. final Car car = Car.create(Car::new); final List<Car> cars = Arrays.asList(car); cars.forEach(Car::collide);
  • 44. final Car car = Car.create(Car::new); final List<Car> cars = Arrays.asList(car); cars.forEach(Car::repair);
  • 45. 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);
  • 46. 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!"); } }
  • 47. 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); }
  • 48. PersonFactory<Person> personFactory = Person::new; Person person = personFactory.create("Peter", "Parker");
  • 49. 5
  • 50. 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();
  • 51. Function<String, Integer> toInteger = Integer::valueOf; Function<String, String> backToString = toInteger.andThen(String::valueOf); backToString.apply("123"); // "123"
  • 52. Supplier<Person> personSupplier = Person::new; personSupplier.get(); // new Person
  • 53. Consumer<Person> greeter = p -> System.out.println("Hello, " + p.firstName); greeter.accept(new Person("Luke", "Skywalker"));
  • 54. 6
  • 55. 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"
  • 56. 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!
  • 57. 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!
  • 58. 7
  • 59.
  • 60. 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 { }
  • 61. void forEach(Consumer<? super T> action) List<Double> temperature = Arrays.asList(20.0, 22.0, 22.5); temperature.forEach(System.out::println);
  • 62. 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);
  • 63. boolean removeIf(Predicate<? super E> filter) List<Double> temperature = Arrays.asList(20.0, 22.0, 22.5); temperature.removeIf(s -> s > 22);
  • 64. void replaceAll(UnaryOperator<E> operator) List<Double> temperature = Arrays.asList(20.0, 22.0, 22.5); temperature.replaceAll(s -> Math.pow(s, 0.5));
  • 65. 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"));
  • 66. 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.
  • 67. 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.
  • 68. 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.
  • 69. 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)
  • 70. 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
  • 71. 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
  • 72. 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)
  • 73. 8
  • 74. Comparator<Person> comparator = (p1, p2) -> p1.firstname.compareTo(p2.firstname);
  • 75. Comparator<Person> comparator = Comparator.comparing(p -> p.lastname)
  • 76. Comparator<Person> comparator = Comparator.comparing(Person::getLastname);
  • 77. Comparator<Person> comparator = (p1, p2) -> { int r = p1.lastname.compareTo(p2.lastname); if (r != 0) return r; return p1.firstname.compareTo(p2.firstname); };
  • 78. Comparator<Person> comparator4 = Comparator .comparing(Person::getLastname) .thenComparing(Person::getFirstname);
  • 79. Comparator<Person> comparator = Comparator .comparing(Person::getLastname) .reverse() .thenComparing(Person::getFirstname);
  • 80. 9
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94. // 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; } );
  • 95. // 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
  • 96.
  • 97. int sum = numbers.stream().reduce(0, Integer::sum);
  • 98. int sumOfWeights = widgets.stream() .reduce(0, (sum, b) -> sum + b.getWeight()) Integer::sum);
  • 99.
  • 100. 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
  • 101. 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));
  • 102. 10
  • 103.
  • 104. 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();
  • 105. 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()
  • 106. Stream<T> limit(long maxSize) Stream<T> distinct() Stream<T> filter(Predicate<? super T> predicate)
  • 107. <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)
  • 108. <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)
  • 109. 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)
  • 110. 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)
  • 111. Object[] toArray() <A> A[] toArray(IntFunction<A[]> generator)
  • 112. void forEach(Consumer<? super T> action) void forEachOrdered(Consumer<? super T> action)
  • 113. <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)
  • 114.
  • 115. public void closure() { List<Supplier<Integer>> list = new ArrayList<>(); for (int i = 1; i <= 5; i++) { list.add(() -> i); } }
  • 116. public void closure() { List<Supplier<Integer>> list = new ArrayList<>(); for (int i = 1; i <= 5; i++) { list.add(() -> i); } } DOES NOT COMPILE The value of « i » changes along the way
  • 117. 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 } COMPILE A new « j » variable is created at each iteration
  • 118. 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 all In this example « j » IS EFFECTIVELY FINAL
  • 119. 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 }
  • 120. 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 } }
  • 121.
  • 122.
  • 124. 11