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

Java 7 (Dolphin) - July 2011
Java 8 (Spider) - March 2014
Java 9 - Sept 2017
Java 10 - March 2018
int million = 1_000_000;
Java
Java 5 (Tiger) - Sept 2004
Java 6 (Mustang) - Dec 2006

Java 7 (Dolphin) - July 2011
Java 8 (Spider) - March 2014
Java 9 - Sept 2017
Java 10 - March 2018
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
Why Java 8
Doing things in parallel
Less code
Minimise Errors
New (functional) solutions
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
}
Consumer<String> con1 = str -> System.out.println(str);
Consumer<String> con1 = System.out::println;
Writing a lambda
Consumer<String> con1 = str -> System.out.println(str);
Consumer<String> con1 = System.out::println;
Writing a lambda
Consumer<String> con1 = str -> System.out.println("- " + str);
Consumer<String> con1 = System.out::println;
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
Puzzler
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.
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
Puzzler
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.
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
Puzzler
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();

}
Don’t do Block Lambda
str1 -> {

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

return str1 + System.currentTimeMillis();

};


this::myMethod
private String myMethod(final String str1) {

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

return str1 + System.currentTimeMillis();

}
Don’t do Block Lambda
beer -> {
String name;
if (beer.getName().contains(" ")) {
name = beer.getName().replace(" ", "");
} else {
name = beer.getName();
}
try {
name += Integer.parseInt(beer.getAlcoholPrecentage().toString());
} catch (NumberFormatException nfe) {
name += beer.getAlcoholPrecentage();
}
return name;
}
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 from 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());
List<Beer> beers = getBeers();
List<String> goodBeers = new ArrayList<>();

for (Beer beer : beers) {

if (beer.getAlcohol() > 7.5) {

goodBeers.add(beer.getName());

}

}
forEach ?
List<Beer> beers = getBeers();
List<String> goodBeers = new ArrayList<>();
beers.forEach(beer -> {
if (beer.getAlcoholPrecentage() > 7.5) { goodBeers.add(beer); }
});
//bad idea
List<Beer> beers = getBeers();
//enrich with ratings
beers.forEach(beer -> beer.setRating(findRating(beer.getName())));
//enrich with reviews
beers.forEach(beer -> beer.setReviews(findReviews(beer.getName())));
forEach ??
List<Beer> beers = getBeers();
beers.stream()
.map(beer -> beer.newBeerWithRating(findRating(beer.getName()))
.map(beer -> beer.newBeerWithReviews(findReviews(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!
beers.stream()
.filter(beer -> beer.getAlcohol() > 7.5)
.filter(beer -> beer.getRating() > 4)
.map(beer -> beer.getName())
.map(beer -> beer.toUpperCase())
.collect(Collectors.toList());
Multiple filters
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 is a Object Oriented Language
Java 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
More …
Java 8 Puzzlers: The Strange, the Bizarre, and the Wonderful

vJug Session by Baruch Sadogursky and Viktor Gamov

https://youtu.be/lu4UTY940tg
Optional - The Mother of All Bikesheds

Devoxx 2016 by Stuart Marks

https://youtu.be/Ej0sss6cq14
Brian Vermeer
@BrianVerm
brian@brianvermeer.nl

More Related Content

What's hot

Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss Andres Almiray
 
Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to MissJava Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to MissAndres Almiray
 
Making the Most of Your Gradle Build
Making the Most of Your Gradle BuildMaking the Most of Your Gradle Build
Making the Most of Your Gradle BuildAndres Almiray
 
Making the Most of Your Gradle Build
Making the Most of Your Gradle BuildMaking the Most of Your Gradle Build
Making the Most of Your Gradle BuildAndres Almiray
 
OSGi and Eclipse RCP
OSGi and Eclipse RCPOSGi and Eclipse RCP
OSGi and Eclipse RCPEric Jain
 
Una Critica a Rails by Luca Guidi
Una Critica a Rails by Luca GuidiUna Critica a Rails by Luca Guidi
Una Critica a Rails by Luca GuidiCodemotion
 
Why Kotlin - Apalon Kotlin Sprint Part 1
Why Kotlin - Apalon Kotlin Sprint Part 1Why Kotlin - Apalon Kotlin Sprint Part 1
Why Kotlin - Apalon Kotlin Sprint Part 1Kirill Rozov
 
Crushing React bugs with Jest and Enzyme
Crushing React bugs with Jest and EnzymeCrushing React bugs with Jest and Enzyme
Crushing React bugs with Jest and EnzymeAll Things Open
 
Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17Andres Almiray
 
To inject or not to inject: CDI is the question
To inject or not to inject: CDI is the questionTo inject or not to inject: CDI is the question
To inject or not to inject: CDI is the questionAntonio Goncalves
 
Тестирование на Android с Dagger 2
Тестирование на Android с Dagger 2Тестирование на Android с Dagger 2
Тестирование на Android с Dagger 2Kirill Rozov
 
Dependency Injection with CDI in 15 minutes
Dependency Injection with CDI in 15 minutesDependency Injection with CDI in 15 minutes
Dependency Injection with CDI in 15 minutesAntonio Goncalves
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 KotlinVMware Tanzu
 

What's hot (20)

Tdd iPhone For Dummies
Tdd iPhone For DummiesTdd iPhone For Dummies
Tdd iPhone For Dummies
 
Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss
 
Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to MissJava Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss
 
Making the Most of Your Gradle Build
Making the Most of Your Gradle BuildMaking the Most of Your Gradle Build
Making the Most of Your Gradle Build
 
Making the Most of Your Gradle Build
Making the Most of Your Gradle BuildMaking the Most of Your Gradle Build
Making the Most of Your Gradle Build
 
OSGi and Eclipse RCP
OSGi and Eclipse RCPOSGi and Eclipse RCP
OSGi and Eclipse RCP
 
Una Critica a Rails by Luca Guidi
Una Critica a Rails by Luca GuidiUna Critica a Rails by Luca Guidi
Una Critica a Rails by Luca Guidi
 
Why Kotlin - Apalon Kotlin Sprint Part 1
Why Kotlin - Apalon Kotlin Sprint Part 1Why Kotlin - Apalon Kotlin Sprint Part 1
Why Kotlin - Apalon Kotlin Sprint Part 1
 
Agile Android
Agile AndroidAgile Android
Agile Android
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
 
Crushing React bugs with Jest and Enzyme
Crushing React bugs with Jest and EnzymeCrushing React bugs with Jest and Enzyme
Crushing React bugs with Jest and Enzyme
 
Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17
 
Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
 
To inject or not to inject: CDI is the question
To inject or not to inject: CDI is the questionTo inject or not to inject: CDI is the question
To inject or not to inject: CDI is the question
 
Annotation processing
Annotation processingAnnotation processing
Annotation processing
 
Core Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug HuntCore Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug Hunt
 
Тестирование на Android с Dagger 2
Тестирование на Android с Dagger 2Тестирование на Android с Dagger 2
Тестирование на Android с Dagger 2
 
Dependency Injection with CDI in 15 minutes
Dependency Injection with CDI in 15 minutesDependency Injection with CDI in 15 minutes
Dependency Injection with CDI in 15 minutes
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
 
groovy & grails - lecture 13
groovy & grails - lecture 13groovy & grails - lecture 13
groovy & grails - lecture 13
 

Similar to Java8 tgtbatu devoxxuk18

Ten common mistakes made in Function Java - iSense Java Summit
Ten common mistakes made in Function Java - iSense Java SummitTen common mistakes made in Function Java - iSense Java Summit
Ten common mistakes made in Function Java - iSense Java SummitBrian Vermeer
 
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 in Function Java
Ten common mistakes made in Function JavaTen common mistakes made in Function Java
Ten common mistakes made in Function JavaBrian 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
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
 
GeeCON 2014 - Functional Programming without Lambdas
GeeCON 2014 - Functional Programming without LambdasGeeCON 2014 - Functional Programming without Lambdas
GeeCON 2014 - Functional Programming without LambdasMattias Severson
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrencykshanth2101
 
Functional aspects of java 8
Functional aspects of java 8Functional aspects of java 8
Functional aspects of java 8Jobaer Chowdhury
 
Retrolambda+bolts
Retrolambda+boltsRetrolambda+bolts
Retrolambda+boltsTom Sun
 
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
 
Clean up your code with C#6
Clean up your code with C#6Clean up your code with C#6
Clean up your code with C#6Rui Carvalho
 
Common mistakes functional java devoxx
Common mistakes functional java devoxxCommon mistakes functional java devoxx
Common mistakes functional java devoxxBrian 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
 

Similar to Java8 tgtbatu devoxxuk18 (20)

Ten common mistakes made in Function Java - iSense Java Summit
Ten common mistakes made in Function Java - iSense Java SummitTen common mistakes made in Function Java - iSense Java Summit
Ten common mistakes made in Function Java - iSense Java Summit
 
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 in Function Java
Ten common mistakes made in Function JavaTen common mistakes made in Function Java
Ten common mistakes made in Function Java
 
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
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
GeeCON 2014 - Functional Programming without Lambdas
GeeCON 2014 - Functional Programming without LambdasGeeCON 2014 - Functional Programming without Lambdas
GeeCON 2014 - Functional Programming without Lambdas
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
 
Functional aspects of java 8
Functional aspects of java 8Functional aspects of java 8
Functional aspects of java 8
 
Retrolambda+bolts
Retrolambda+boltsRetrolambda+bolts
Retrolambda+bolts
 
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
 
EMFPath
EMFPathEMFPath
EMFPath
 
Clean up your code with C#6
Clean up your code with C#6Clean up your code with C#6
Clean up your code with C#6
 
Common mistakes functional java devoxx
Common mistakes functional java devoxxCommon mistakes functional java devoxx
Common mistakes functional java devoxx
 
Common mistakes made with Functional Java
Common mistakes made with Functional JavaCommon mistakes made with Functional Java
Common mistakes made with Functional Java
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 

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
 
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 (10)

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

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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
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
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
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
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
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
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 

Recently uploaded (20)

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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
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...
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
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
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 

Java8 tgtbatu devoxxuk18

  • 1. Java (8) Brian Vermeer (@BrianVerm)
  • 2.
  • 3. Java Java 5 (Tiger) - Sept 2004 Java 6 (Mustang) - Dec 2006
 Java 7 (Dolphin) - July 2011 Java 8 (Spider) - March 2014 Java 9 - Sept 2017 Java 10 - March 2018
  • 4. int million = 1_000_000;
  • 5. Java Java 5 (Tiger) - Sept 2004 Java 6 (Mustang) - Dec 2006
 Java 7 (Dolphin) - July 2011 Java 8 (Spider) - March 2014 Java 9 - Sept 2017 Java 10 - March 2018
  • 6. Java 8 March 2014 Working from a more functional perspective
 Some “life changing” code constructions In retrospect: 
 What is GOOD, BAD and UGLY
  • 8. Disclaimer Best Practices are based on opinions
 
 Different conclusions are possible Think, and make your own judgement
  • 9. Why Java 8 Doing things in parallel Less code Minimise Errors New (functional) solutions
  • 10.
  • 11. Lambda Anonymous Inner Function.
 (Nameless function without boilerplate code) Satisfying a Functional Interface
 (Interface with basically 1 abstract method) <parameters> -> <function body>
  • 12. 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
  • 13. 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
  • 14. 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
  • 15. 
 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
  • 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, new Comparator<Beer>() {
 @Override
 public int compare(Beer b1, Beer b2) {
 return b1.getName().compareTo(b2.getName());
 }
 });
 Java 7 Comparator
  • 17. 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
  • 18. 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
  • 19. 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
 }
 
 

  • 20. 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
 } 

  • 21. 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 }
  • 22. Consumer<String> con1 = str -> System.out.println(str); Consumer<String> con1 = System.out::println; Writing a lambda
  • 23. Consumer<String> con1 = str -> System.out.println(str); Consumer<String> con1 = System.out::println; Writing a lambda Consumer<String> con1 = str -> System.out.println("- " + str); Consumer<String> con1 = System.out::println;
  • 24. 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 Puzzler 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.
  • 25. 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 Puzzler 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.
  • 26. 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 Puzzler 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
  • 27. Block Lambda str1 -> {
 System.out.println("Hello world");
 return str1 + System.currentTimeMillis();
 }; 

  • 28. 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();
 }
  • 29. Don’t do Block Lambda str1 -> {
 System.out.println("Hello world");
 return str1 + System.currentTimeMillis();
 }; 
 this::myMethod private String myMethod(final String str1) {
 System.out.println("Hello world");
 return str1 + System.currentTimeMillis();
 }
  • 30. Don’t do Block Lambda beer -> { String name; if (beer.getName().contains(" ")) { name = beer.getName().replace(" ", ""); } else { name = beer.getName(); } try { name += Integer.parseInt(beer.getAlcoholPrecentage().toString()); } catch (NumberFormatException nfe) { name += beer.getAlcoholPrecentage(); } return name; }
  • 31. 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
  • 32. 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
  • 34. Exception handling How can I throw CHECKED exceptions from inside Java 8 streams/ lambdas?
  • 35. 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.
  • 36. Checked Exceptions & Lambda public Beer doSomething(Beer beer) throws IsEmptyException { …} Function <Beer,Beer> fBeer = beer -> doSomething(beer) 

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

  • 38. 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
  • 39. 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)
  • 40. 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))
  • 42. 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)
  • 43. 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(); } 

  • 44. 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!
  • 45. Using Optional Don’t use unnecessary optionals //avoid if (Optional.ofNullable(str1).isPresent()) { … } Optional.ofNullable(str1).ifPresent(x -> doSomething(x)); //instead if (str1 == null) { … } 

  • 46. 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); 

  • 47. 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
  • 49. What is Stream ( in Java8 ) Not a data structure, not storage Flow of data derived from a Collection Intermediate result Lazy evaluated by nature Can transform data, cannot mutate data Can create a pipeline of function that can be evaluated
  • 50. 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
  • 51. List<Beer> beers = getBeers(); List<String> goodBeers = new ArrayList<>();
 for (Beer beer : beers) {
 if (beer.getAlcohol() > 7.5) {
 goodBeers.add(beer.getName());
 }
 } Stream Example
  • 52. 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());
  • 53. List<Beer> beers = getBeers(); List<String> goodBeers = new ArrayList<>();
 for (Beer beer : beers) {
 if (beer.getAlcohol() > 7.5) {
 goodBeers.add(beer.getName());
 }
 } forEach ? List<Beer> beers = getBeers(); List<String> goodBeers = new ArrayList<>(); beers.forEach(beer -> { if (beer.getAlcoholPrecentage() > 7.5) { goodBeers.add(beer); } }); //bad idea
  • 54. List<Beer> beers = getBeers(); //enrich with ratings beers.forEach(beer -> beer.setRating(findRating(beer.getName()))); //enrich with reviews beers.forEach(beer -> beer.setReviews(findReviews(beer.getName()))); forEach ?? List<Beer> beers = getBeers(); beers.stream() .map(beer -> beer.newBeerWithRating(findRating(beer.getName())) .map(beer -> beer.newBeerWithReviews(findReviews(beer.getName())) .collect(Collectors.toList())
  • 55. 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
  • 56. 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
  • 57. 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
  • 58. 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!
  • 59. beers.stream() .filter(beer -> beer.getAlcohol() > 7.5) .filter(beer -> beer.getRating() > 4) .map(beer -> beer.getName()) .map(beer -> beer.toUpperCase()) .collect(Collectors.toList()); Multiple filters
  • 60. IntStream.iterate(0, i -> i + 1)
 .forEach(i -> System.out.println(i)); Infinite stream
  • 61. 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));
  • 62. Infinite stream //“subtle” mistake, this will run forever IntStream.iterate(0, i -> ( i + 1) % 2)
 .distinct()
 .limit(10)
 .forEach(i -> System.out.println(i));
  • 63. 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));
  • 64. 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.
  • 65. 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
  • 66. Summary Java is a Object Oriented Language Java 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
  • 67. More … Java 8 Puzzlers: The Strange, the Bizarre, and the Wonderful
 vJug Session by Baruch Sadogursky and Viktor Gamov
 https://youtu.be/lu4UTY940tg Optional - The Mother of All Bikesheds
 Devoxx 2016 by Stuart Marks
 https://youtu.be/Ej0sss6cq14