SlideShare ist ein Scribd-Unternehmen logo
1 von 61
Downloaden Sie, um offline zu lesen
Java 8
Brian Vermeer (@BrianVerm)JBCNConf 2017
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
Java 5 (Tiger) - Sept 2004
Java 6 (Mustang) - Dec 2006

Java 7 (Dolphin) - July 2011
Java 8 (Spider) - March 2014
Java 9 - July 2017 ???
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;
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:

Weitere ähnliche Inhalte

Was ist angesagt?

Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
Pramod Kumar
 
Google Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG NantesGoogle Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG Nantes
mikaelbarbero
 
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
julien.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, 2012
Anton Arhipov
 

Was ist angesagt? (20)

Google guava
Google guavaGoogle guava
Google guava
 
Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
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 & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG NantesGoogle Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG Nantes
 
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 - 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
 
Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's tests
 
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
 
My java file
My java fileMy java file
My java file
 
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
 
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
 

Ähnlich wie Java 8: the good, the bad and the ugly (JBCNConf 2017)

Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with Groovy
James Williams
 

Ähnlich wie Java 8: the good, the bad and the ugly (JBCNConf 2017) (20)

Ten mistakes functional java
Ten mistakes functional javaTen mistakes functional java
Ten mistakes functional 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
 
GeeCON 2014 - Functional Programming without Lambdas
GeeCON 2014 - Functional Programming without LambdasGeeCON 2014 - Functional Programming without Lambdas
GeeCON 2014 - Functional Programming without Lambdas
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
EMFPath
EMFPathEMFPath
EMFPath
 
Retrolambda+bolts
Retrolambda+boltsRetrolambda+bolts
Retrolambda+bolts
 
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
 
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
NodeJS Spring style Inversifyjs
NodeJS Spring style InversifyjsNodeJS Spring style Inversifyjs
NodeJS Spring style Inversifyjs
 
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
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with Groovy
 
Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 Groovytesting
 
What's New in Groovy 1.6?
What's New in Groovy 1.6?What's New in Groovy 1.6?
What's New in Groovy 1.6?
 
Project Lambda: Evolution of Java
Project Lambda: Evolution of JavaProject Lambda: Evolution of Java
Project Lambda: Evolution of Java
 

Mehr von Brian Vermeer

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

Kürzlich hochgeladen

%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Kürzlich hochgeladen (20)

%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 

Java 8: the good, the bad and the ugly (JBCNConf 2017)

  • 1. Java 8 Brian Vermeer (@BrianVerm)JBCNConf 2017
  • 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 Java 5 (Tiger) - Sept 2004 Java 6 (Mustang) - Dec 2006
 Java 7 (Dolphin) - July 2011 Java 8 (Spider) - March 2014 Java 9 - July 2017 ???
  • 5. Java 8 March 2014 Working from a more functional perspective
 Some “life changing” code constructions In retrospect: 
 What is GOOD, BAD and UGLY
  • 7. Disclaimer Best Practices are based on opinions
 
 Different conclusions are possible Think, and make your own judgement
  • 8. Why Java 8 Doing things in parallel Less code Minimise Errors New (functional) solutions
  • 9.
  • 10. Lambda Anonymous Inner Function.
 (Nameless function without boilerplate code) Satisfying a Functional Interface
 (Interface with basically 1 abstract method) <parameters> -> <function body>
  • 11. 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
  • 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; 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; public BiFunction<String, String, String> bifunc1 = (str1, str2) -> str1 + "-" + str2; Functional Interfaces
  • 14. 
 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
  • 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, 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, (b1,b2) -> b1.getName().compareTo(b2.getName()));
 
 beers.sort((b1,b2) -> b1.getName().compareTo(b2.getName())); 
 Java 8 Comparator
  • 18. 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
 }
 
 

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

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

  • 27. 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();
 }
  • 28. 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
  • 29. 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
  • 31. Exception handling How can I throw CHECKED exceptions from inside Java 8 streams/ lambdas?
  • 32. 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.
  • 33. Checked Exceptions & Lambda public Beer doSomething(Beer beer) throws IsEmptyException { …} Function <Beer,Beer> fBeer = beer -> doSomething(beer) 

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

  • 35. 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
  • 36. 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)
  • 37. 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))
  • 39. 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)
  • 40. 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(); } 

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

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

  • 44. 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
  • 46. 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
  • 47. 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
  • 48. List<Beer> beers = getBeers(); List<String> goodBeers = new ArrayList<>();
 for (Beer beer : beers) {
 if (beer.getAlcohol() > 7.5) {
 goodBeers.add(beer.getName());
 }
 } Stream Example
  • 49. 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());
  • 50. 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
  • 51. 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
  • 52. 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
  • 53. 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!
  • 54. IntStream.iterate(0, i -> i + 1)
 .forEach(i -> System.out.println(i)); Infinite stream
  • 55. 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));
  • 56. Infinite stream //“subtle” mistake, this will run forever IntStream.iterate(0, i -> ( i + 1) % 2)
 .distinct()
 .limit(10)
 .forEach(i -> System.out.println(i));
  • 57. 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));
  • 58. 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.
  • 59. 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
  • 60. 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