SlideShare a Scribd company logo
1 of 58
Download to read offline
Java 8
Brian Vermeer (@BrianVerm)Oracle Code Brussels
Java
Java 5 (Tiger) - Sept 2004
Java 6 (Mustang) - Dec 2006

Java 7 (Dolphin) - July 2011
Java 8 (Spider) - March 2014
Java 9 - July 2017 ???
int million = 1_000_000;
Java 8
March 2014
Working from a more functional
perspective

Some “life changing” code constructions
In retrospect: 

What is GOOD, BAD and UGLY
Brian Vermeer
Software Engineer
Disclaimer
Best Practices are based on opinions



Different conclusions are possible
Think, and make your own
judgement
• Easy to Parallelise
• Fewer lines of code
• New solutions to Problems
• Minimise Errors
Lambda
Anonymous Inner Function.

(Nameless function without boilerplate code)
Satisfying a Functional Interface

(Interface with basically 1 abstract method)
<parameters> -> <function body>
public interface Predicate<T> {
boolean test(T t);
}
public interface Function<T,R> {
R apply(T t);
}
public interface Consumer<T> {
void accept(T t);
}
public interface Supplier<T> {
T get();
}
Functional Interfaces
public Predicate<Integer> pred = i -> i % 2 == 0;


public Consumer<Integer> cons = i -> System.out.println(i);


public Supplier<Double> sup = () -> Math.random();


public Function<Integer, String> func = i -> "Input is " + i;
Functional Interfaces
public Predicate<Integer> pred = i -> i % 2 == 0;


public Consumer<Integer> cons = i -> System.out.println(i);


public Supplier<Double> sup = () -> Math.random();


public Function<Integer, String> func = i -> "Input is " + i;
public BiFunction<String, String, String> bifunc1 =
(str1, str2) -> str1 + "-" + str2;
Functional Interfaces


public interface Comparator<T> {
int compare(T o1, T o2);
}
public interface Callable<V> {
V call() throws Exception;
}
public interface Runnable {
public void run();
}
Functional Interfaces
List<Beer> beers = new ArrayList<>();

beers.add(new Beer("La Chouffe", 8.0));

beers.add(new Beer("Duvel", 8.5));

beers.add(new Beer("Jupiler", 5.2));





Collections.sort(beers, new Comparator<Beer>() {

@Override

public int compare(Beer b1, Beer b2) {

return b1.getName().compareTo(b2.getName());

}

});

Java 7 Comparator
List<Beer> beers = new ArrayList<>();

beers.add(new Beer("La Chouffe", 8.0));

beers.add(new Beer("Duvel", 8.5));

beers.add(new Beer("Jupiler", 5.2));





Collections.sort(beers, new Comparator<Beer>() {

@Override

public int compare(Beer b1, Beer b2) {

return b1.getName().compareTo(b2.getName());

}

});

Java 7 Comparator
List<Beer> beers = new ArrayList<>();

beers.add(new Beer("La Chouffe", 8.0));

beers.add(new Beer("Duvel", 8.5));

beers.add(new Beer("Jupiler", 5.2));)





Collections.sort(beers, (b1,b2) -> b1.getName().compareTo(b2.getName()));



beers.sort((b1,b2) -> b1.getName().compareTo(b2.getName()));


Java 8 Comparator
Abstraction
private void logUpper(String str) {

//super interesting code

System.out.println(str.toUpperCase());

//even more interesting code

}



private void logLower(String str) {

//super interesting code

System.out.println(str.toLowerCase());

//even more interesting code

}





Abstraction
private void logUpper(String string) {

doFoo(string, s -> s.toUpperCase());

}



private void logLower(String string) {

doFoo(string, s -> s.toLowerCase());

}



private void doFoo(String str, Function<String, String> func) {

//super interesting code

System.out.println(func.apply(str));

//even more interesting code

}


Writing a Lamda
//Single line Lambda
int1 -> (int1 / 2) * 3;
//Multi line Lambda (block lambda)
int1 -> { //do Some code
// do Some more code
// return something
}
Puzzler
List<Beer> beers = new ArrayList<>();

beers.add(new Beer("La Chouffe", 8.0));

beers.add(new Beer("Duvel", 8.5));

beers.add(new Beer("Jupiler", 5.2));)
beers.sort((b1,b2) -> b1.getAlcohol().compareTo(b2.getAlcohol())); //1
beers.sort((b1,b2) -> { b1.getAlcohol().compareTo(b2.getAlcohol())); } //2


A) Line 1 compiles , Line 2 does not.
B) Line 2 compiles , Line 1 does not.
C) Both lines will compile.
D) I don’t care, just give me one of these beers.
Puzzler
List<Beer> beers = new ArrayList<>();

beers.add(new Beer("La Chouffe", 8.0));

beers.add(new Beer("Duvel", 8.5));

beers.add(new Beer("Jupiler", 5.2));)
beers.sort((b1,b2) -> b1.getAlcohol().compareTo(b2.getAlcohol())); //1
beers.sort((b1,b2) -> { b1.getAlcohol().compareTo(b2.getAlcohol())); } //2


A) Line 1 compiles , Line 2 does not.
B) Line 2 compiles , Line 1 does not.
C) Both lines will compile.
D) I don’t care, just give me one of these beers.
Puzzler
List<Beer> beers = new ArrayList<>();

beers.add(new Beer("La Chouffe", 8.0));

beers.add(new Beer("Duvel", 8.5));

beers.add(new Beer("Jupiler", 5.2));)
beers.sort((b1,b2) -> b1.getAlcohol().compareTo(b2.getAlcohol())); //1
beers.sort((b1,b2) -> { b1.getAlcohol().compareTo(b2.getAlcohol())); } //2


A) Line 1 compiles , Line 2 does not.
B) Line 2 compiles , Line 1 does not.
C) Both lines will compile.
D) I don’t care, just give me one of these beers.
Implicit return
Explicit return
Block Lambda
str1 -> {

System.out.println("Hello world");

return str1 + System.currentTimeMillis();

};


Don’t do Block Lambda
str1 -> {

System.out.println("Hello world");

return str1 + System.currentTimeMillis();

};


str1 -> myMethod(str1);
private String myMethod(final String str1) {

System.out.println("Hello world");

return str1 + System.currentTimeMillis();

}
Type inference
(Beer b1,Beer b2) -> b1.getAlcohol().compareTo(b2.getAlcohol())
(b1,b2) -> b1.getAlcohol().compareTo(b2.getAlcohol())
Make use of automatic type inferencing.
Only specify types if compiler does not understand
Parentheses
(int1) -> int1 * 2 - 1
int1 -> int1 * 2 - 1
Dont’s use parentheses if not needed
(6-3)+2 is the same as 6 - 3 + 2
Exceptions
Exception handling
How can I throw CHECKED exceptions from inside Java 8 streams/
lambdas?
Exception handling
How can I throw CHECKED exceptions from inside Java 8 streams/
lambdas?
The simple answer to your question is: 

You can't, at least not directly.
Checked Exceptions & Lambda
public Beer doSomething(Beer beer) throws IsEmptyException { …}
Function <Beer,Beer> fBeer = beer -> doSomething(beer)


Checked Exceptions & Lambda
public Beer doSomething(Beer beer) throws IsEmptyException { …}
Function <Beer,Beer> fBeer = beer -> doSomething(beer)


Checked Exceptions & Lambda
public Beer doSomething(Beer beer) throws IsEmptyException { …}
beer -> {

try{

return doSomething(beer);

} catch (IsEmptyException e) {

throw new RuntimeException(e);

}

};
//not very pretty
Checked Exceptions & Lambda
public Beer doSomething(Beer beer) throws IsEmptyException { …}
private Beer wrappedDoSomeThing(Beer beer) {

try{

return doSomething(beer);

} catch (IsEmptyException e) {

throw new RuntimeException(e);

}

}
beer -> wrappedDoSomeThing(beer)
Exception Utility
@FunctionalInterface

public interface CheckedFunction<T, R> {

public R apply(T t) throws Throwable;

}
public static <T, R> Function<T, R> wrap(CheckedFunction<T, R> function) {

return t -> {

try {

return function.apply(t);

} catch (Throwable ex) {

throw new RuntimeException(ex);

}

};

};
wrap(beer -> doSomething(beer))
Optional
Optional
New type added in Java 8
Wrapper class around a value that might be absent
Designed to tackle the NULL reference problem
Different opinions (awesome or ugly)
Optional
Optional<String>

- empty

- literal String (“Hello World”);
public String giveMeAString() { return “Hello World” }
public String giveMeAString() { return null }
public Optional<String> giveMeAString() { return Optional.of(“Hello World”);}
public Optional<String> giveMeAString() { return Optional.empty(); }


Optional
Optional<String> a = Optional.of(“Hello World”);
Optional<String> b = Optional.empty();
Optional<String> c = null //please avoid this


Be careful
Optional can be null
Always avoid this in your own code!
Using Optional
Don’t use unnecessary optionals
//avoid
if (Optional.ofNullable(str1).isPresent()) { … }
Optional.ofNullable(str1).ifPresent(x -> doSomething(x));
//instead
if (str1 == null) { … }


Using Optional
Use Optional in a more functional way
public Optional<Beer> findBeer(String name) { … }
Beer b = findBeer(name).orElse(Beer.DEFAULT);
Beer b1 = findBeer(name).orElseThrow(NotFoundException::new);


Optional
Optional can have 3 options, be aware ….
Never assign to null in your own code.
Choose when to use Optional en stick to that

- everywhere

- only what is publicly available

- don’t use it at all
Optional is designed as return type, not as input type
Streams
What is Stream ( in Java8 )
Not a data structure, not storage
Flow of data derived form a Collection
Intermediate result
Lazy evaluated by nature
Can transform data, cannot mutate data
Can create a pipeline of function that can be evaluated
JAVA 8 Streams
stringLists.stream()

.map(str -> str.toUpperCase())

.collect(Collectors.toList());
Intermediate
filter 

distinct

map 

flatMap

Terminal
reduce

collect

toArray

count

max

min

limit 

skip

sorted

peek
findAny

findFirst

forEach

allMatch

anyMatch
List<Beer> beers = getBeers();
List<String> goodBeers = new ArrayList<>();

for (Beer beer : beers) {

if (beer.getAlcohol() > 7.5) {

goodBeers.add(beer.getName());

}

}
Stream Example
List<Beer> beers = getBeers();
List<String> goodBeers = new ArrayList<>();

for (Beer beer : beers) {

if (beer.getAlcohol() > 7.5) {

goodBeers.add(beer.getName());

}

}
Stream Example
List<Beer> beers = getBeers();
List<String> goodBeers = beers.stream()

.filter(beer -> beer.getAlcohol() > 7.5)

.map(beer -> beer.getName())

.collect(Collectors.toList());
Puzzler
List<String> teams = new ArrayList<>();

teams.add("alpha");

teams.add("bravo");

teams.add("charlie");

teams.add("delta");

Stream<String> teamsInMission = teams.stream();

teams.remove("bravo");

teams.add("echo");

teamsInMission.forEach(team -> System.out.println(team));
A) alpha, bravo, charlie, delta
B) alpha, bravo, charlie, delta, ConcurrentModificationException
C) alpha, charlie, delta, echo
D) ConcurrentModificationException
Puzzler
List<String> teams = new ArrayList<>();

teams.add("alpha");

teams.add("bravo");

teams.add("charlie");

teams.add("delta");

Stream<String> teamsInMission = teams.stream();

teams.remove("bravo");

teams.add("echo");

teamsInMission.forEach(team -> System.out.println(team));
A) alpha, bravo, charlie, delta
B) alpha, bravo, charlie, delta, ConcurrentModificationException
C) alpha, charlie, delta, echo
D) ConcurrentModificationException
List<Beer> beers = getBeers();

Stream<Beer> beerStream = beers.stream();



beerStream.forEach(b ->System.out.println(b.getName())); //1


beerStream.forEach(b ->System.out.println(b.getAlcohol())); //2
Only use a Stream once
Line 2 will give: 



java.lang.IllegalStateException: stream has already been operated upon or
closed
beers.stream()

.limit(10)

.map(i -> i.getAlcohol())

.peek(i -> {

if (i > 7.0)

throw new RuntimeException();

});
Consume the stream
Don’t forget to consume the stream!
IntStream.iterate(0, i -> i + 1)

.forEach(i -> System.out.println(i));
Infinite stream
IntStream.iterate(0, i -> i + 1)

.forEach(i -> System.out.println(i));
Infinite stream
IntStream.iterate(0, i -> i + 1)

.limit(10)

.forEach(i -> System.out.println(i));
Infinite stream
//“subtle” mistake, this will run forever
IntStream.iterate(0, i -> ( i + 1) % 2)

.distinct()

.limit(10)

.forEach(i -> System.out.println(i));
Infinite stream
//“subtle” mistake, this will run forever
IntStream.iterate(0, i -> ( i + 1) % 2)

.distinct()

.limit(10)

.forEach(i -> System.out.println(i));
//parallel makes it even worse!!!!
IntStream.iterate(0, i -> ( i + 1) % 2)
.parallel()
.distinct()

.limit(10)

.forEach(i -> System.out.println(i));
Watch out with parallel
Watch out with parallel in general
Parallel stream all use the common fork-join
thread pool
Parallel can slow you down.
Streams
Don’t replace every loop with Stream
Be careful with infinite streams
Only uses streams once
Be very careful with parallel
A stream is not a data structure
Stream pipelines don’t do anything until consumed
Summary
Java 8 is a Object Oriented Language
Java 8 is not a Functional Language
There are some nice new “functional”
code constructions you can use
Use them with care
Don’t be a cowboy
Brian Vermeer
@BrianVerm
brian@brianvermeer.nl
//Thanks for attending
//Now its time for some:

More Related Content

What's hot

Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesGanesh Samarthyam
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습DoHyun Jung
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleGeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleAnton Arhipov
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner codeMite Mitreski
 
Google Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG NantesGoogle Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG Nantesmikaelbarbero
 
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
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydneyjulien.ponge
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Anton Arhipov
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's testsSean P. Floyd
 
Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17Andres Almiray
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistAnton Arhipov
 

What's hot (20)

Google guava
Google guavaGoogle guava
Google guava
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
 
Migrating to JUnit 5
Migrating to JUnit 5Migrating to JUnit 5
Migrating to JUnit 5
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleGeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassle
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
Unit testing concurrent code
Unit testing concurrent codeUnit testing concurrent code
Unit testing concurrent code
 
Google Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG NantesGoogle Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG Nantes
 
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
 
Tdd iPhone For Dummies
Tdd iPhone For DummiesTdd iPhone For Dummies
Tdd iPhone For Dummies
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydney
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's tests
 
My java file
My java fileMy java file
My java file
 
Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
 

Similar to Java 8: the good, the bad and the ugly (Oracle Code Brussels 2017)

Ten mistakes functional java
Ten mistakes functional javaTen mistakes functional java
Ten mistakes functional javaBrian Vermeer
 
Common mistakes functional java | Oracle Code One 2018
Common mistakes functional java | Oracle Code One 2018Common mistakes functional java | Oracle Code One 2018
Common mistakes functional java | Oracle Code One 2018Brian Vermeer
 
Common mistakes functional java vjug
Common mistakes functional java vjugCommon mistakes functional java vjug
Common mistakes functional java vjugBrian Vermeer
 
Ten common mistakes made with Functional Java JBCNConf18
Ten common mistakes made with Functional Java JBCNConf18Ten common mistakes made with Functional Java JBCNConf18
Ten common mistakes made with Functional Java JBCNConf18Brian Vermeer
 
Common mistakes functional java snyk
Common mistakes functional java snykCommon mistakes functional java snyk
Common mistakes functional java snykBrian Vermeer
 
Writing better functional java code - devnexus
Writing better functional java code  - devnexusWriting better functional java code  - devnexus
Writing better functional java code - devnexusBrian Vermeer
 
Writing better functional java code devnexus
Writing better functional java code   devnexusWriting better functional java code   devnexus
Writing better functional java code devnexusBrian Vermeer
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
 
The Ring programming language version 1.5.3 book - Part 27 of 184
The Ring programming language version 1.5.3 book - Part 27 of 184The Ring programming language version 1.5.3 book - Part 27 of 184
The Ring programming language version 1.5.3 book - Part 27 of 184Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 32 of 202
The Ring programming language version 1.8 book - Part 32 of 202The Ring programming language version 1.8 book - Part 32 of 202
The Ring programming language version 1.8 book - Part 32 of 202Mahmoud Samir Fayed
 
Functional aspects of java 8
Functional aspects of java 8Functional aspects of java 8
Functional aspects of java 8Jobaer Chowdhury
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsRasan Samarasinghe
 
The Ring programming language version 1.5 book - Part 5 of 31
The Ring programming language version 1.5 book - Part 5 of 31The Ring programming language version 1.5 book - Part 5 of 31
The Ring programming language version 1.5 book - Part 5 of 31Mahmoud Samir Fayed
 
The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212Mahmoud Samir Fayed
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressionsLogan Chien
 
The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196Mahmoud Samir Fayed
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Ganesh Samarthyam
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummiesknutmork
 
The Ring programming language version 1.2 book - Part 16 of 84
The Ring programming language version 1.2 book - Part 16 of 84The Ring programming language version 1.2 book - Part 16 of 84
The Ring programming language version 1.2 book - Part 16 of 84Mahmoud Samir Fayed
 

Similar to Java 8: the good, the bad and the ugly (Oracle Code Brussels 2017) (20)

Ten mistakes functional java
Ten mistakes functional javaTen mistakes functional java
Ten mistakes functional java
 
Common mistakes functional java | Oracle Code One 2018
Common mistakes functional java | Oracle Code One 2018Common mistakes functional java | Oracle Code One 2018
Common mistakes functional java | Oracle Code One 2018
 
Common mistakes functional java vjug
Common mistakes functional java vjugCommon mistakes functional java vjug
Common mistakes functional java vjug
 
Ten common mistakes made with Functional Java JBCNConf18
Ten common mistakes made with Functional Java JBCNConf18Ten common mistakes made with Functional Java JBCNConf18
Ten common mistakes made with Functional Java JBCNConf18
 
Common mistakes functional java snyk
Common mistakes functional java snykCommon mistakes functional java snyk
Common mistakes functional java snyk
 
Writing better functional java code - devnexus
Writing better functional java code  - devnexusWriting better functional java code  - devnexus
Writing better functional java code - devnexus
 
Writing better functional java code devnexus
Writing better functional java code   devnexusWriting better functional java code   devnexus
Writing better functional java code devnexus
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
The Ring programming language version 1.5.3 book - Part 27 of 184
The Ring programming language version 1.5.3 book - Part 27 of 184The Ring programming language version 1.5.3 book - Part 27 of 184
The Ring programming language version 1.5.3 book - Part 27 of 184
 
The Ring programming language version 1.8 book - Part 32 of 202
The Ring programming language version 1.8 book - Part 32 of 202The Ring programming language version 1.8 book - Part 32 of 202
The Ring programming language version 1.8 book - Part 32 of 202
 
Functional aspects of java 8
Functional aspects of java 8Functional aspects of java 8
Functional aspects of java 8
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
 
The Ring programming language version 1.5 book - Part 5 of 31
The Ring programming language version 1.5 book - Part 5 of 31The Ring programming language version 1.5 book - Part 5 of 31
The Ring programming language version 1.5 book - Part 5 of 31
 
The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 
The Ring programming language version 1.2 book - Part 16 of 84
The Ring programming language version 1.2 book - Part 16 of 84The Ring programming language version 1.2 book - Part 16 of 84
The Ring programming language version 1.2 book - Part 16 of 84
 

More from Brian Vermeer

Stranger Danger: Your Java Attack Surface Just Got Bigger | JBCNConf 2022
Stranger Danger: Your Java Attack Surface Just Got Bigger | JBCNConf 2022Stranger Danger: Your Java Attack Surface Just Got Bigger | JBCNConf 2022
Stranger Danger: Your Java Attack Surface Just Got Bigger | JBCNConf 2022Brian Vermeer
 
Teqnation 19 - Live Hacking
Teqnation 19 - Live Hacking Teqnation 19 - Live Hacking
Teqnation 19 - Live Hacking Brian Vermeer
 
Don't be a trojan - Codemotion Amsterdam 2019
Don't be a trojan - Codemotion Amsterdam 2019Don't be a trojan - Codemotion Amsterdam 2019
Don't be a trojan - Codemotion Amsterdam 2019Brian Vermeer
 
Don't be a trojan - Java2Days 2018
Don't be a trojan - Java2Days 2018Don't be a trojan - Java2Days 2018
Don't be a trojan - Java2Days 2018Brian Vermeer
 
Common mistakes made with Functional Java
Common mistakes made with Functional JavaCommon mistakes made with Functional Java
Common mistakes made with Functional JavaBrian Vermeer
 
Common mistakes functional java devoxx
Common mistakes functional java devoxxCommon mistakes functional java devoxx
Common mistakes functional java devoxxBrian Vermeer
 
Identity Theft : Developers are key
Identity Theft : Developers are keyIdentity Theft : Developers are key
Identity Theft : Developers are keyBrian Vermeer
 
Identity theft jfall17
Identity theft jfall17Identity theft jfall17
Identity theft jfall17Brian Vermeer
 
Identity theft: Developers are key - JavaZone17
Identity theft: Developers are key - JavaZone17Identity theft: Developers are key - JavaZone17
Identity theft: Developers are key - JavaZone17Brian Vermeer
 
Identity theft blue4it nljug
Identity theft blue4it nljugIdentity theft blue4it nljug
Identity theft blue4it nljugBrian Vermeer
 
Identity theft: Developers are key - JFokus 2017
Identity theft: Developers are key - JFokus 2017Identity theft: Developers are key - JFokus 2017
Identity theft: Developers are key - JFokus 2017Brian Vermeer
 

More from Brian Vermeer (12)

Stranger Danger: Your Java Attack Surface Just Got Bigger | JBCNConf 2022
Stranger Danger: Your Java Attack Surface Just Got Bigger | JBCNConf 2022Stranger Danger: Your Java Attack Surface Just Got Bigger | JBCNConf 2022
Stranger Danger: Your Java Attack Surface Just Got Bigger | JBCNConf 2022
 
Teqnation 19 - Live Hacking
Teqnation 19 - Live Hacking Teqnation 19 - Live Hacking
Teqnation 19 - Live Hacking
 
Don't be a trojan - Codemotion Amsterdam 2019
Don't be a trojan - Codemotion Amsterdam 2019Don't be a trojan - Codemotion Amsterdam 2019
Don't be a trojan - Codemotion Amsterdam 2019
 
Don't be a trojan - Java2Days 2018
Don't be a trojan - Java2Days 2018Don't be a trojan - Java2Days 2018
Don't be a trojan - Java2Days 2018
 
Common mistakes made with Functional Java
Common mistakes made with Functional JavaCommon mistakes made with Functional Java
Common mistakes made with Functional Java
 
Common mistakes functional java devoxx
Common mistakes functional java devoxxCommon mistakes functional java devoxx
Common mistakes functional java devoxx
 
Don't be a Trojan
Don't be a TrojanDon't be a Trojan
Don't be a Trojan
 
Identity Theft : Developers are key
Identity Theft : Developers are keyIdentity Theft : Developers are key
Identity Theft : Developers are key
 
Identity theft jfall17
Identity theft jfall17Identity theft jfall17
Identity theft jfall17
 
Identity theft: Developers are key - JavaZone17
Identity theft: Developers are key - JavaZone17Identity theft: Developers are key - JavaZone17
Identity theft: Developers are key - JavaZone17
 
Identity theft blue4it nljug
Identity theft blue4it nljugIdentity theft blue4it nljug
Identity theft blue4it nljug
 
Identity theft: Developers are key - JFokus 2017
Identity theft: Developers are key - JFokus 2017Identity theft: Developers are key - JFokus 2017
Identity theft: Developers are key - JFokus 2017
 

Recently uploaded

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 

Recently uploaded (20)

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 

Java 8: the good, the bad and the ugly (Oracle Code Brussels 2017)

  • 1. Java 8 Brian Vermeer (@BrianVerm)Oracle Code Brussels
  • 2. Java Java 5 (Tiger) - Sept 2004 Java 6 (Mustang) - Dec 2006
 Java 7 (Dolphin) - July 2011 Java 8 (Spider) - March 2014 Java 9 - July 2017 ???
  • 3. int million = 1_000_000;
  • 4. Java 8 March 2014 Working from a more functional perspective
 Some “life changing” code constructions In retrospect: 
 What is GOOD, BAD and UGLY
  • 6. Disclaimer Best Practices are based on opinions
 
 Different conclusions are possible Think, and make your own judgement
  • 7. • Easy to Parallelise • Fewer lines of code • New solutions to Problems • Minimise Errors
  • 8.
  • 9. Lambda Anonymous Inner Function.
 (Nameless function without boilerplate code) Satisfying a Functional Interface
 (Interface with basically 1 abstract method) <parameters> -> <function body>
  • 10. public interface Predicate<T> { boolean test(T t); } public interface Function<T,R> { R apply(T t); } public interface Consumer<T> { void accept(T t); } public interface Supplier<T> { T get(); } Functional Interfaces
  • 11. public Predicate<Integer> pred = i -> i % 2 == 0; 
 public Consumer<Integer> cons = i -> System.out.println(i); 
 public Supplier<Double> sup = () -> Math.random(); 
 public Function<Integer, String> func = i -> "Input is " + i; Functional Interfaces
  • 12. public Predicate<Integer> pred = i -> i % 2 == 0; 
 public Consumer<Integer> cons = i -> System.out.println(i); 
 public Supplier<Double> sup = () -> Math.random(); 
 public Function<Integer, String> func = i -> "Input is " + i; public BiFunction<String, String, String> bifunc1 = (str1, str2) -> str1 + "-" + str2; Functional Interfaces
  • 13. 
 public interface Comparator<T> { int compare(T o1, T o2); } public interface Callable<V> { V call() throws Exception; } public interface Runnable { public void run(); } Functional Interfaces
  • 14. List<Beer> beers = new ArrayList<>();
 beers.add(new Beer("La Chouffe", 8.0));
 beers.add(new Beer("Duvel", 8.5));
 beers.add(new Beer("Jupiler", 5.2));
 
 
 Collections.sort(beers, new Comparator<Beer>() {
 @Override
 public int compare(Beer b1, Beer b2) {
 return b1.getName().compareTo(b2.getName());
 }
 });
 Java 7 Comparator
  • 15. List<Beer> beers = new ArrayList<>();
 beers.add(new Beer("La Chouffe", 8.0));
 beers.add(new Beer("Duvel", 8.5));
 beers.add(new Beer("Jupiler", 5.2));
 
 
 Collections.sort(beers, new Comparator<Beer>() {
 @Override
 public int compare(Beer b1, Beer b2) {
 return b1.getName().compareTo(b2.getName());
 }
 });
 Java 7 Comparator
  • 16. List<Beer> beers = new ArrayList<>();
 beers.add(new Beer("La Chouffe", 8.0));
 beers.add(new Beer("Duvel", 8.5));
 beers.add(new Beer("Jupiler", 5.2));)
 
 
 Collections.sort(beers, (b1,b2) -> b1.getName().compareTo(b2.getName()));
 
 beers.sort((b1,b2) -> b1.getName().compareTo(b2.getName())); 
 Java 8 Comparator
  • 17. Abstraction private void logUpper(String str) {
 //super interesting code
 System.out.println(str.toUpperCase());
 //even more interesting code
 }
 
 private void logLower(String str) {
 //super interesting code
 System.out.println(str.toLowerCase());
 //even more interesting code
 }
 
 

  • 18. Abstraction private void logUpper(String string) {
 doFoo(string, s -> s.toUpperCase());
 }
 
 private void logLower(String string) {
 doFoo(string, s -> s.toLowerCase());
 }
 
 private void doFoo(String str, Function<String, String> func) {
 //super interesting code
 System.out.println(func.apply(str));
 //even more interesting code
 } 

  • 19. Writing a Lamda //Single line Lambda int1 -> (int1 / 2) * 3; //Multi line Lambda (block lambda) int1 -> { //do Some code // do Some more code // return something }
  • 20. Puzzler List<Beer> beers = new ArrayList<>();
 beers.add(new Beer("La Chouffe", 8.0));
 beers.add(new Beer("Duvel", 8.5));
 beers.add(new Beer("Jupiler", 5.2));) beers.sort((b1,b2) -> b1.getAlcohol().compareTo(b2.getAlcohol())); //1 beers.sort((b1,b2) -> { b1.getAlcohol().compareTo(b2.getAlcohol())); } //2 
 A) Line 1 compiles , Line 2 does not. B) Line 2 compiles , Line 1 does not. C) Both lines will compile. D) I don’t care, just give me one of these beers.
  • 21. Puzzler List<Beer> beers = new ArrayList<>();
 beers.add(new Beer("La Chouffe", 8.0));
 beers.add(new Beer("Duvel", 8.5));
 beers.add(new Beer("Jupiler", 5.2));) beers.sort((b1,b2) -> b1.getAlcohol().compareTo(b2.getAlcohol())); //1 beers.sort((b1,b2) -> { b1.getAlcohol().compareTo(b2.getAlcohol())); } //2 
 A) Line 1 compiles , Line 2 does not. B) Line 2 compiles , Line 1 does not. C) Both lines will compile. D) I don’t care, just give me one of these beers.
  • 22. Puzzler List<Beer> beers = new ArrayList<>();
 beers.add(new Beer("La Chouffe", 8.0));
 beers.add(new Beer("Duvel", 8.5));
 beers.add(new Beer("Jupiler", 5.2));) beers.sort((b1,b2) -> b1.getAlcohol().compareTo(b2.getAlcohol())); //1 beers.sort((b1,b2) -> { b1.getAlcohol().compareTo(b2.getAlcohol())); } //2 
 A) Line 1 compiles , Line 2 does not. B) Line 2 compiles , Line 1 does not. C) Both lines will compile. D) I don’t care, just give me one of these beers. Implicit return Explicit return
  • 23. Block Lambda str1 -> {
 System.out.println("Hello world");
 return str1 + System.currentTimeMillis();
 }; 

  • 24. Don’t do Block Lambda str1 -> {
 System.out.println("Hello world");
 return str1 + System.currentTimeMillis();
 }; 
 str1 -> myMethod(str1); private String myMethod(final String str1) {
 System.out.println("Hello world");
 return str1 + System.currentTimeMillis();
 }
  • 25. Type inference (Beer b1,Beer b2) -> b1.getAlcohol().compareTo(b2.getAlcohol()) (b1,b2) -> b1.getAlcohol().compareTo(b2.getAlcohol()) Make use of automatic type inferencing. Only specify types if compiler does not understand
  • 26. Parentheses (int1) -> int1 * 2 - 1 int1 -> int1 * 2 - 1 Dont’s use parentheses if not needed (6-3)+2 is the same as 6 - 3 + 2
  • 28. Exception handling How can I throw CHECKED exceptions from inside Java 8 streams/ lambdas?
  • 29. Exception handling How can I throw CHECKED exceptions from inside Java 8 streams/ lambdas? The simple answer to your question is: 
 You can't, at least not directly.
  • 30. Checked Exceptions & Lambda public Beer doSomething(Beer beer) throws IsEmptyException { …} Function <Beer,Beer> fBeer = beer -> doSomething(beer) 

  • 31. Checked Exceptions & Lambda public Beer doSomething(Beer beer) throws IsEmptyException { …} Function <Beer,Beer> fBeer = beer -> doSomething(beer) 

  • 32. Checked Exceptions & Lambda public Beer doSomething(Beer beer) throws IsEmptyException { …} beer -> {
 try{
 return doSomething(beer);
 } catch (IsEmptyException e) {
 throw new RuntimeException(e);
 }
 }; //not very pretty
  • 33. Checked Exceptions & Lambda public Beer doSomething(Beer beer) throws IsEmptyException { …} private Beer wrappedDoSomeThing(Beer beer) {
 try{
 return doSomething(beer);
 } catch (IsEmptyException e) {
 throw new RuntimeException(e);
 }
 } beer -> wrappedDoSomeThing(beer)
  • 34. Exception Utility @FunctionalInterface
 public interface CheckedFunction<T, R> {
 public R apply(T t) throws Throwable;
 } public static <T, R> Function<T, R> wrap(CheckedFunction<T, R> function) {
 return t -> {
 try {
 return function.apply(t);
 } catch (Throwable ex) {
 throw new RuntimeException(ex);
 }
 };
 }; wrap(beer -> doSomething(beer))
  • 36. Optional New type added in Java 8 Wrapper class around a value that might be absent Designed to tackle the NULL reference problem Different opinions (awesome or ugly)
  • 37. Optional Optional<String>
 - empty
 - literal String (“Hello World”); public String giveMeAString() { return “Hello World” } public String giveMeAString() { return null } public Optional<String> giveMeAString() { return Optional.of(“Hello World”);} public Optional<String> giveMeAString() { return Optional.empty(); } 

  • 38. Optional Optional<String> a = Optional.of(“Hello World”); Optional<String> b = Optional.empty(); Optional<String> c = null //please avoid this 
 Be careful Optional can be null Always avoid this in your own code!
  • 39. Using Optional Don’t use unnecessary optionals //avoid if (Optional.ofNullable(str1).isPresent()) { … } Optional.ofNullable(str1).ifPresent(x -> doSomething(x)); //instead if (str1 == null) { … } 

  • 40. Using Optional Use Optional in a more functional way public Optional<Beer> findBeer(String name) { … } Beer b = findBeer(name).orElse(Beer.DEFAULT); Beer b1 = findBeer(name).orElseThrow(NotFoundException::new); 

  • 41. Optional Optional can have 3 options, be aware …. Never assign to null in your own code. Choose when to use Optional en stick to that
 - everywhere
 - only what is publicly available
 - don’t use it at all Optional is designed as return type, not as input type
  • 43. What is Stream ( in Java8 ) Not a data structure, not storage Flow of data derived form a Collection Intermediate result Lazy evaluated by nature Can transform data, cannot mutate data Can create a pipeline of function that can be evaluated
  • 44. JAVA 8 Streams stringLists.stream()
 .map(str -> str.toUpperCase())
 .collect(Collectors.toList()); Intermediate filter 
 distinct
 map 
 flatMap
 Terminal reduce
 collect
 toArray
 count
 max
 min
 limit 
 skip
 sorted
 peek findAny
 findFirst
 forEach
 allMatch
 anyMatch
  • 45. List<Beer> beers = getBeers(); List<String> goodBeers = new ArrayList<>();
 for (Beer beer : beers) {
 if (beer.getAlcohol() > 7.5) {
 goodBeers.add(beer.getName());
 }
 } Stream Example
  • 46. List<Beer> beers = getBeers(); List<String> goodBeers = new ArrayList<>();
 for (Beer beer : beers) {
 if (beer.getAlcohol() > 7.5) {
 goodBeers.add(beer.getName());
 }
 } Stream Example List<Beer> beers = getBeers(); List<String> goodBeers = beers.stream()
 .filter(beer -> beer.getAlcohol() > 7.5)
 .map(beer -> beer.getName())
 .collect(Collectors.toList());
  • 47. Puzzler List<String> teams = new ArrayList<>();
 teams.add("alpha");
 teams.add("bravo");
 teams.add("charlie");
 teams.add("delta");
 Stream<String> teamsInMission = teams.stream();
 teams.remove("bravo");
 teams.add("echo");
 teamsInMission.forEach(team -> System.out.println(team)); A) alpha, bravo, charlie, delta B) alpha, bravo, charlie, delta, ConcurrentModificationException C) alpha, charlie, delta, echo D) ConcurrentModificationException
  • 48. Puzzler List<String> teams = new ArrayList<>();
 teams.add("alpha");
 teams.add("bravo");
 teams.add("charlie");
 teams.add("delta");
 Stream<String> teamsInMission = teams.stream();
 teams.remove("bravo");
 teams.add("echo");
 teamsInMission.forEach(team -> System.out.println(team)); A) alpha, bravo, charlie, delta B) alpha, bravo, charlie, delta, ConcurrentModificationException C) alpha, charlie, delta, echo D) ConcurrentModificationException
  • 49. List<Beer> beers = getBeers();
 Stream<Beer> beerStream = beers.stream();
 
 beerStream.forEach(b ->System.out.println(b.getName())); //1 
 beerStream.forEach(b ->System.out.println(b.getAlcohol())); //2 Only use a Stream once Line 2 will give: 
 
 java.lang.IllegalStateException: stream has already been operated upon or closed
  • 50. beers.stream()
 .limit(10)
 .map(i -> i.getAlcohol())
 .peek(i -> {
 if (i > 7.0)
 throw new RuntimeException();
 }); Consume the stream Don’t forget to consume the stream!
  • 51. IntStream.iterate(0, i -> i + 1)
 .forEach(i -> System.out.println(i)); Infinite stream
  • 52. IntStream.iterate(0, i -> i + 1)
 .forEach(i -> System.out.println(i)); Infinite stream IntStream.iterate(0, i -> i + 1)
 .limit(10)
 .forEach(i -> System.out.println(i));
  • 53. Infinite stream //“subtle” mistake, this will run forever IntStream.iterate(0, i -> ( i + 1) % 2)
 .distinct()
 .limit(10)
 .forEach(i -> System.out.println(i));
  • 54. Infinite stream //“subtle” mistake, this will run forever IntStream.iterate(0, i -> ( i + 1) % 2)
 .distinct()
 .limit(10)
 .forEach(i -> System.out.println(i)); //parallel makes it even worse!!!! IntStream.iterate(0, i -> ( i + 1) % 2) .parallel() .distinct()
 .limit(10)
 .forEach(i -> System.out.println(i));
  • 55. Watch out with parallel Watch out with parallel in general Parallel stream all use the common fork-join thread pool Parallel can slow you down.
  • 56. Streams Don’t replace every loop with Stream Be careful with infinite streams Only uses streams once Be very careful with parallel A stream is not a data structure Stream pipelines don’t do anything until consumed
  • 57. Summary Java 8 is a Object Oriented Language Java 8 is not a Functional Language There are some nice new “functional” code constructions you can use Use them with care Don’t be a cowboy