SlideShare a Scribd company logo
Ten common mistakes
made with Function Java
Brian Vermeer (@BrianVerm)Java Summit
Ten common mistakes made in Function Java - iSense Java Summit
Ten common mistakes made in Function Java - iSense Java Summit
Ten common mistakes made in Function Java - iSense Java Summit
Brian Vermeer
Software Engineer
Doing too much in a single lambda
Lambda Expression
In computer programming, a lambda expression is a function definition
that is not bound to an identifier. Anonymous functions are often:[1]
• arguments being passed to higher-order functions, or
• used for constructing the result of a higher-order function that
needs to return a function.
Lambda in Java
Anonymous Inner functions
Satisfy a Functional Interface
They only exist in runtime
Single Line <input> -> <output> or Block <input> -> { function body }
Example
public void execute() {
Beer grolsch = new Beer("Grolsche", 4.3);
String result = handleBeer(grolsch,
beer -> grolsch.getName() + "-" + grolsch.getAlcohol());
System.out.println(result);
}
private String handleBeer(Beer beer, Function<Beer, String> func) {
System.out.println("handling beer " + beer.getName());
return func.apply(beer);
}
//Output : Grolsche-4.3
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;
}
Transform to a methode
private String createFullName (Beer 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;
}
handleBeer(grolsch, this::createFullName);
Returning a Stream
A stream is NOT a
data structure
A stream is NOT a
data structure
A stream is NOT a
data structure
What is Stream ( in Java)
Flow of data derived from a Collection
Can create a pipeline of function that can be evaluated
Intermediate result
Lazy evaluated by nature
Can transform data, cannot mutate data
JAVA 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();

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
public Stream<Beer> getMeMyBeers()
public void execute() {
getMeMyBeers() //don’t know if it is consumed yet!!!!
…
}
Don’t return a Stream
Not Consuming a Stream
Ten common mistakes made in Function Java - iSense Java Summit
Ten common mistakes made in Function Java - iSense Java Summit
Ten common mistakes made in Function Java - iSense Java Summit
Ten common mistakes made in Function Java - iSense Java Summit
List<Beer> beers = List.of(new Beer("Heineken", 5.2), new Beer("Delirium
Tremens", 9.0), new Beer("Amstel", 5.1));
beers.stream()

.limit(10)

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

.peek(i -> {

if (i > 7.0)

throw new RuntimeException();

});
Consume the stream
Ten common mistakes made in Function Java - iSense Java Summit
List<Beer> beers = List.of(new Beer("Heineken", 5.2), new Beer("Delirium
Tremens", 9.0), new Beer("Amstel", 5.1));
beers.stream()

.limit(10)

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

.peek(i -> {

if (i > 7.0)

throw new RuntimeException();

})
.forEach(System.out::println);
Consume the stream
5.2
Exception in thread "main" java.lang.RuntimeException
Mutable Object
Functional Programming
In computer science, functional programming is a programming
paradigma style of building the structure and elements of computer
programs that treats computation as the evaluation of mathematical
functions and avoids changing-state and mutable data.
It is a declarative programming paradigm, which means programming is
done with expressions or declarations instead of statements.
— wikipedia
Ten common mistakes made in Function Java - iSense Java Summit
– Kevlin Henney
“Asking a question should not
change the answer, nor
should asking it twice”
Immutable objects
Less moving parts
Easier to reason about code
No need to keep a mental map of the state an object is in.
Stream cannot mutate
private final List<Beer> beers = List.of(new Beer("Heineken", 5.2),
new Beer("Amstel", 5.1));
public void execute() {
List<Beer> beersNew = beers.stream()
.map(beer -> beer.setName(“foo”)) //not allowed
.collect(Collectors.toList());
}
Stream should not mutate !
private class Beer {
String name;
Double alcohol;
public Beer setName(String name){
this.name = name;
return this;
}
}
private final List<Beer> beers = List.of(new Beer("Heineken", 5.2), new Beer("Amstel",
5.1));
public void execute() {
List<Beer> beersNew = beers.stream()
.map(beer -> beer.setName("foo"))
.collect(Collectors.toList());
System.out.println(beers);
System.out.println(beersNew);
}
Stream should not mutate !
private class Beer {
String name;
Double alcohol;
public Beer setName(String name){
this.name = name;
return this;
}
}
private final List<Beer> beers = List.of(new Beer("Heineken", 5.2), new Beer("Amstel",
5.1));
public void execute() {
List<Beer> beersNew = beers.stream()
.map(beer -> beer.setName("foo"))
.collect(Collectors.toList());
System.out.println(beers);
System.out.println(beersNew);
}
Return a new copy
private class Beer {
String name;
Double alcohol;
public Beer withName(String name){
return new Beer(name, this.alcohol);
}
}
private final List<Beer> beers = List.of(new Beer("Heineken", 5.2), new Beer("Amstel",
5.1));
public void execute() {
List<Beer> beersNew = beers.stream()
.map(beer -> beer.withName("foo"))
.collect(Collectors.toList());
System.out.println(beers);
System.out.println(beersNew);
}
Overusing forEach
forEach()
Terminal functional on a stream.
Takes a consumer.
Can be used to apply side effects.
for-loop without the external iterator
simple forEach example
List<String> names = List.of("James", "Trisha", "Joshua",
"Jessica","Simon", “Heather");
names.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
mutation with forEach
List<Beer> beers = List.of(new Beer("Heineken", 5.2), new
Beer("Amstel", 5.1));
beers.stream()
.forEach(beer -> beer.setAlcohol(0.0));
overusing forEach
private class Beer {
String name;
Double alcohol;
List<String> reviews;
Integer rating;
}
List<Beer> beers = List.of(new Beer("Heineken", 5.2), new Beer("Amstel", 5.1));
//enrich with ratings
beers.stream().forEach(beer -> beer.setRating(findRating(beer.getName())));
//enrich with reviews
beers.stream().forEach(beer -> beer.setReviews(findReviews(beer.getName())));
…
Order of operations
Assignment
Beers -> Brewer -> Country
I want the first 3 unique brewers countries from the beer library as comma separated String
beerLib.stream()
.map(Beer::getBrewer)
.distinct()
.limit(3)
.map(Brewer::getCountry)
.map(String::toUpperCase)
.collect(Collectors.joining(“,”));
Assignment
Beers -> Brewer -> Country
I want the first 3 unique brewers countries from the beer library as comma separated String
beerLib.stream()
.map(Beer::getBrewer)
.distinct()
.limit(3)
.map(Brewer::getCountry)
.map(String::toUpperCase)
.collect(Collectors.joining(“,”));
// wrong
Assignment
Beers -> Brewer -> Country
I want the first 3 unique brewers countries from the beer library as comma separated String
beerLib.stream()
.map(Beer::getBrewer)
.map(Brewer::getCountry)
.map(String::toUpperCase)
.distinct()
.limit(3)
.collect(Collectors.joining(“,”));
// correct
Infinite stream
IntStream.iterate(0, i -> ( i + 1) % 2)

.distinct()

.limit(10)

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

.distinct()

.limit(10)

.forEach(i -> System.out.println(i));

// will run forever
IntStream.iterate(0, i -> ( i + 1) % 2)

.limit(10)

.distinct()

.forEach(i -> System.out.println(i));
//will terminate
Infinite stream
IntStream.iterate(0, i -> ( i + 1) % 2)

.parallel()
.distinct()

.limit(10)

.forEach(i -> System.out.println(i));

// will run forever on all threads.
Solution
1. Look closely at the order of operations

- prevent incorrect answers



2. Only use infinite streams when absolutely necessary.
rather use: 

IntStream.range(0,10);
IntStream.rangeClosed(0,10);
IntStream.iterate(0, i -> i < 10, i -> i + 1); //java 9 and up
Getting an Optional
Optional
Java’s implementation of the Maybe Monad
Encapsulation to handle possible null value
Consider it a wrapper where a value can be absent
Force the user to unpack the Optional before using it.
Optional
Optional<String> c = null //please avoid this
public void execute() {
Optional<String> maybeString = getText();
String unpacked = maybeString.get();
}
Unpack Optional
public void execute() {
Optional<String> maybeString = getText();
String unpacked = maybeString.get();
}
Unpack Optional
NoSuchElementException
public void execute() {
Optional<String> maybeString = getText();
String unpacked = maybeString.get();
}
Unpack Optional
public void execute() {
Optional<String> maybeString = getText();
if (maybeString.isPresent()) {
String unpacked = maybeString.get();
}
}
NoSuchElementException
Unpack Optional
public void execute() {
Optional<String> maybeString = getText();
maybeString.ifPresent( str -> /* doSomething */ );
}
public void execute() {
Optional<String> maybeString = getText();
maybeString.map(str -> str + “.");
}
What else ..??
Alternative flow
- orElse()
- orElseGet()
- orElseThrow()
orElseThrow
public void execute() {

Optional<String> maybeString = Optional.empty();

maybeString

.map(this::runIfExist)

.orElseThrow(() -> new RuntimeException("Optional was empty"));

}
orElse
public void execute() {

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

String newString = maybeString

.map(this::runIfExist)

.orElse(runIfEmpty());

System.out.println(newString);

}

private String runIfExist(String str) {

System.out.println("only run if optional is filled ");

return str;

}

private String runIfEmpty() {

System.out.println("only run if empty");

return "empty";

}
orElse
public void execute() {

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

String newString = maybeString

.map(this::runIfExist)

.orElse(runIfEmpty());

System.out.println(newString);

}

private String runIfExist(String str) {

System.out.println("only run if optional is filled ");

return str;

}

private String runIfEmpty() {

System.out.println("only run if empty");

return "empty";

}
only run if optional is filled
only run if empty
foo
orElseGet
public void execute() {

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

String newString = maybeString

.map(this::runIfExist)

.orElseGet(() -> runIfEmpty());

System.out.println(newString);

}

private String runIfExist(String str) {

System.out.println("only run if optional is filled ");

return str;

}

private String runIfEmpty() {

System.out.println("only run if empty");

return "empty";

}
orElseGet
public void execute() {

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

String newString = maybeString

.map(this::runIfExist)

.orElseGet(() -> runIfEmpty());

System.out.println(newString);

}

private String runIfExist(String str) {

System.out.println("only run if optional is filled ");

return str;

}

private String runIfEmpty() {

System.out.println("only run if empty");

return "empty";

}
only run if optional is filled
foo
what else?
- When using orElse(x), make sure x doesn’t contain any side effects
- Only use orElse() to assign a default value
- Use orElseGet() to run an alternative flow
Exceptions
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 { …}
beerLib.stream()
.map(beer -> {

try{

return doSomething(beer);

} catch (IsEmptyException e) {

throw new RuntimeException(e);

}

};)
.collect(Collectors.toList());
//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);

}

}
beerLib.stream()
.map(this::wrappedDoSomeThing)
.collect(Collectors.toList());
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);

}

};

};
beerLib.stream()
.map(beer -> wrap(doSomething(beer)))
.collect(Collectors.toList());
Either type
public class Either<L, R> {
private final L left;
private final R right;
private Either(L left, R right) {
this.left = left;
this.right = right;
}
public static <L,R> Either<L,R> Left( L value) {
return new Either(value, null);
}
public static <L,R> Either<L,R> Right( R value) {
return new Either(null, value);
} …
}
Either type
private Either<Exception, String> canGoWrong(Integer input) {
if (input > 10) {
return Either.Left(new RuntimeException("larger then 10"));
}
return Either.Right("["+input+"]");
}
List<Either<Exception, String>> canGoWrongs = IntStream.range(0,12)
.mapToObj(i -> canGoWrong(i))
.collect(Collectors.toList());
Either type
private Either<Exception, String> canGoWrong(Integer input) {
if (input > 10) {
return Either.Left(new RuntimeException("larger then 10"));
}
return Either.Right(“["+input+"]");
}
List<Either<Exception, String>> canGoWrongs = IntStream.range(0,12)
.mapToObj(i -> canGoWrong(i))
.collect(Collectors.toList());
canGoWrongs.stream()
.map(e -> e.mapRight(s -> s.toUpperCase()))
.flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))
.forEach(System.out::println);
More with streams
//java 9
List myList = List.of(1,2,3,4,5)
//pre Java9
List myList = Arrays.asList(new String[] {“a”,"b","c"});
Creating collections
//java 9
List myList = List.of(1,2,3,4,5)
//pre Java9
List myList = Arrays.asList(new String[] {"a","b","c"});
// since Java 8
List myList = Stream.of("a","b","c","d").collect(Collectors.toList());
Creating collections
private Beer foo(){...}
private Beer bar(){...}
private Beer fooBar(){…}
Beer myBeer = new Beer();
Beer result = fooBar(bar(foo(myBeer)));
Using Stream.of
private Beer foo(){...}
private Beer bar(){...}
private Beer fooBar(){…}
Beer myBeer = new Beer();
Beer result = fooBar(bar(foo(myBeer)));
Using Stream.of
Beer result = Stream.of(myBeer)
.map(this::foo)

.map(this::bar)

.map(this::fooBar)

.findFirst().get();
String sentence = "The quick fox jumps over the lazy dog. ";
String[] words = sentence
.trim()
.toUpperCase()
.split(" ");
for(String word : words) {
System.out.println(word);
}
Using Stream.of
String sentence = "The quick fox jumps over the lazy dog. ";
String[] words = sentence
.trim()
.toUpperCase()
.split(" ");
for(String word : words) {
System.out.println(word);
}
Stream.of(sentence)
.map(String::trim)
.map(String::toUpperCase)
.map(str -> str.split(" "))
.flatMap(array -> Arrays.stream(array))
.forEach(System.out::println);
Using Stream.of
Brian Vermeer
@BrianVerm
brian@brianvermeer.nl
Java Summit

More Related Content

What's hot (19)

Java 8: the good, the bad and the ugly (JBCNConf 2017)
Java 8: the good, the bad and the ugly (JBCNConf 2017)Java 8: the good, the bad and the ugly (JBCNConf 2017)
Java 8: the good, the bad and the ugly (JBCNConf 2017)
Brian Vermeer
 
Java 8: the good, the bad and the ugly (Oracle Code Brussels 2017)
Java 8: the good, the bad and the ugly (Oracle Code Brussels 2017)Java 8: the good, the bad and the ugly (Oracle Code Brussels 2017)
Java 8: the good, the bad and the ugly (Oracle Code Brussels 2017)
Brian Vermeer
 
Flask SQLAlchemy
Flask SQLAlchemy Flask SQLAlchemy
Flask SQLAlchemy
Eueung Mulyana
 
Rest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemyRest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemy
Alessandro Cucci
 
Flask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuthFlask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuth
Eueung Mulyana
 
Java(8) The Good, The Bad and the Ugly
Java(8) The Good, The Bad and the UglyJava(8) The Good, The Bad and the Ugly
Java(8) The Good, The Bad and the Ugly
Brian Vermeer
 
In-depth analysis of Kotlin Flows
In-depth analysis of Kotlin FlowsIn-depth analysis of Kotlin Flows
In-depth analysis of Kotlin Flows
GlobalLogic Ukraine
 
How to export import a mysql database via ssh in aws lightsail wordpress rizw...
How to export import a mysql database via ssh in aws lightsail wordpress rizw...How to export import a mysql database via ssh in aws lightsail wordpress rizw...
How to export import a mysql database via ssh in aws lightsail wordpress rizw...
AlexRobert25
 
Endevor api an introduction to the endevor application programming interface
Endevor api   an introduction to the endevor application programming interface Endevor api   an introduction to the endevor application programming interface
Endevor api an introduction to the endevor application programming interface
Kevin Grimes
 
Filling the flask
Filling the flaskFilling the flask
Filling the flask
Jason Myers
 
Smolder @Silex
Smolder @SilexSmolder @Silex
Smolder @Silex
Jeen Lee
 
Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18
Lar21
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
it-people
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
Max Claus Nunes
 
Apache cheat sheet
Apache cheat sheetApache cheat sheet
Apache cheat sheet
Lam Hoang
 
SVN Hook
SVN HookSVN Hook
SVN Hook
Thomas Weinert
 
SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniques
Ben Scheirman
 
Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
Ganesh Samarthyam
 
TRunner
TRunnerTRunner
TRunner
Jeen Lee
 
Java 8: the good, the bad and the ugly (JBCNConf 2017)
Java 8: the good, the bad and the ugly (JBCNConf 2017)Java 8: the good, the bad and the ugly (JBCNConf 2017)
Java 8: the good, the bad and the ugly (JBCNConf 2017)
Brian Vermeer
 
Java 8: the good, the bad and the ugly (Oracle Code Brussels 2017)
Java 8: the good, the bad and the ugly (Oracle Code Brussels 2017)Java 8: the good, the bad and the ugly (Oracle Code Brussels 2017)
Java 8: the good, the bad and the ugly (Oracle Code Brussels 2017)
Brian Vermeer
 
Rest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemyRest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemy
Alessandro Cucci
 
Flask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuthFlask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuth
Eueung Mulyana
 
Java(8) The Good, The Bad and the Ugly
Java(8) The Good, The Bad and the UglyJava(8) The Good, The Bad and the Ugly
Java(8) The Good, The Bad and the Ugly
Brian Vermeer
 
In-depth analysis of Kotlin Flows
In-depth analysis of Kotlin FlowsIn-depth analysis of Kotlin Flows
In-depth analysis of Kotlin Flows
GlobalLogic Ukraine
 
How to export import a mysql database via ssh in aws lightsail wordpress rizw...
How to export import a mysql database via ssh in aws lightsail wordpress rizw...How to export import a mysql database via ssh in aws lightsail wordpress rizw...
How to export import a mysql database via ssh in aws lightsail wordpress rizw...
AlexRobert25
 
Endevor api an introduction to the endevor application programming interface
Endevor api   an introduction to the endevor application programming interface Endevor api   an introduction to the endevor application programming interface
Endevor api an introduction to the endevor application programming interface
Kevin Grimes
 
Filling the flask
Filling the flaskFilling the flask
Filling the flask
Jason Myers
 
Smolder @Silex
Smolder @SilexSmolder @Silex
Smolder @Silex
Jeen Lee
 
Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18
Lar21
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
it-people
 
Apache cheat sheet
Apache cheat sheetApache cheat sheet
Apache cheat sheet
Lam Hoang
 

More from Brian Vermeer (14)

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
Brian 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 2019
Brian Vermeer
 
Writing better functional java code devnexus
Writing better functional java code   devnexusWriting better functional java code   devnexus
Writing better functional java code devnexus
Brian 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 2018
Brian Vermeer
 
Don't be a Trojan
Don't be a TrojanDon't be a Trojan
Don't be a Trojan
Brian 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 Java
Brian Vermeer
 
Java8 tgtbatu devoxxuk18
Java8 tgtbatu devoxxuk18Java8 tgtbatu devoxxuk18
Java8 tgtbatu devoxxuk18
Brian Vermeer
 
Identity Theft : Developers are key
Identity Theft : Developers are keyIdentity Theft : Developers are key
Identity Theft : Developers are key
Brian Vermeer
 
Identity theft jfall17
Identity theft jfall17Identity theft jfall17
Identity theft jfall17
Brian Vermeer
 
Java8 tgtbatu javaone
Java8 tgtbatu javaoneJava8 tgtbatu javaone
Java8 tgtbatu javaone
Brian Vermeer
 
Identity theft: Developers are key - JavaZone17
Identity theft: Developers are key - JavaZone17Identity theft: Developers are key - JavaZone17
Identity theft: Developers are key - JavaZone17
Brian Vermeer
 
Identity theft blue4it nljug
Identity theft blue4it nljugIdentity theft blue4it nljug
Identity theft blue4it nljug
Brian 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 2017
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 2022
Brian 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 2019
Brian Vermeer
 
Writing better functional java code devnexus
Writing better functional java code   devnexusWriting better functional java code   devnexus
Writing better functional java code devnexus
Brian 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 2018
Brian 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 Java
Brian Vermeer
 
Java8 tgtbatu devoxxuk18
Java8 tgtbatu devoxxuk18Java8 tgtbatu devoxxuk18
Java8 tgtbatu devoxxuk18
Brian Vermeer
 
Identity Theft : Developers are key
Identity Theft : Developers are keyIdentity Theft : Developers are key
Identity Theft : Developers are key
Brian Vermeer
 
Identity theft jfall17
Identity theft jfall17Identity theft jfall17
Identity theft jfall17
Brian Vermeer
 
Java8 tgtbatu javaone
Java8 tgtbatu javaoneJava8 tgtbatu javaone
Java8 tgtbatu javaone
Brian Vermeer
 
Identity theft: Developers are key - JavaZone17
Identity theft: Developers are key - JavaZone17Identity theft: Developers are key - JavaZone17
Identity theft: Developers are key - JavaZone17
Brian Vermeer
 
Identity theft blue4it nljug
Identity theft blue4it nljugIdentity theft blue4it nljug
Identity theft blue4it nljug
Brian 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 2017
Brian Vermeer
 

Recently uploaded (20)

Advance Sales Commission Payments in Odoo
Advance Sales Commission Payments in OdooAdvance Sales Commission Payments in Odoo
Advance Sales Commission Payments in Odoo
AxisTechnolabs
 
Optimising Claims Management with Claims Processing Systems
Optimising Claims Management with Claims Processing SystemsOptimising Claims Management with Claims Processing Systems
Optimising Claims Management with Claims Processing Systems
Insurance Tech Services
 
BIS Safety Software Canada - EHS SOFTWARE
BIS Safety Software Canada - EHS SOFTWAREBIS Safety Software Canada - EHS SOFTWARE
BIS Safety Software Canada - EHS SOFTWARE
BIS Safety
 
Field service report Luzon.pptxxxxxxxxxxxxxxxx
Field service report Luzon.pptxxxxxxxxxxxxxxxxField service report Luzon.pptxxxxxxxxxxxxxxxx
Field service report Luzon.pptxxxxxxxxxxxxxxxx
kashinathgpsgc
 
Skilling up your dev team - 8 things to consider when skilling-up your dev team
Skilling up your dev team - 8 things to consider when skilling-up your dev teamSkilling up your dev team - 8 things to consider when skilling-up your dev team
Skilling up your dev team - 8 things to consider when skilling-up your dev team
Derk-Jan de Grood
 
Progecad 2025 Professional Cracked [Latest]
Progecad 2025 Professional Cracked [Latest]Progecad 2025 Professional Cracked [Latest]
Progecad 2025 Professional Cracked [Latest]
Luisa Weist
 
arvr & metaverse development services.pdf
arvr & metaverse development services.pdfarvr & metaverse development services.pdf
arvr & metaverse development services.pdf
marketing810348
 
Shortcomings of EHS Software – And How to Overcome Them
Shortcomings of EHS Software – And How to Overcome ThemShortcomings of EHS Software – And How to Overcome Them
Shortcomings of EHS Software – And How to Overcome Them
TECH EHS Solution
 
Frontier AI Regulation: What form should it take?
Frontier AI Regulation: What form should it take?Frontier AI Regulation: What form should it take?
Frontier AI Regulation: What form should it take?
Petar Radanliev
 
CFCamp2025 - Keynote Day 1 led by Luis Majano.pdf
CFCamp2025 - Keynote Day 1 led by Luis Majano.pdfCFCamp2025 - Keynote Day 1 led by Luis Majano.pdf
CFCamp2025 - Keynote Day 1 led by Luis Majano.pdf
Ortus Solutions, Corp
 
How OnePlan & Microsoft 365 Ensure Strategic Alignment with AI-Powered Portfo...
How OnePlan & Microsoft 365 Ensure Strategic Alignment with AI-Powered Portfo...How OnePlan & Microsoft 365 Ensure Strategic Alignment with AI-Powered Portfo...
How OnePlan & Microsoft 365 Ensure Strategic Alignment with AI-Powered Portfo...
OnePlan Solutions
 
What's-New-with-BoxLang-Brad Wood.pptx.pdf
What's-New-with-BoxLang-Brad Wood.pptx.pdfWhat's-New-with-BoxLang-Brad Wood.pptx.pdf
What's-New-with-BoxLang-Brad Wood.pptx.pdf
Ortus Solutions, Corp
 
Getting Started with BoxLang - CFCamp 2025.pdf
Getting Started with BoxLang - CFCamp 2025.pdfGetting Started with BoxLang - CFCamp 2025.pdf
Getting Started with BoxLang - CFCamp 2025.pdf
Ortus Solutions, Corp
 
Daily Agile Snippets That Boost Team Focus and Flexibility
Daily Agile Snippets That Boost Team Focus and FlexibilityDaily Agile Snippets That Boost Team Focus and Flexibility
Daily Agile Snippets That Boost Team Focus and Flexibility
Orangescrum
 
Why-Choose-an-Authorised-Microsoft-Reseller.pptx
Why-Choose-an-Authorised-Microsoft-Reseller.pptxWhy-Choose-an-Authorised-Microsoft-Reseller.pptx
Why-Choose-an-Authorised-Microsoft-Reseller.pptx
Michael cole
 
15 Years of Insights from a TDD Practitioner (NDC Oslo)
15 Years of Insights from a TDD Practitioner (NDC Oslo)15 Years of Insights from a TDD Practitioner (NDC Oslo)
15 Years of Insights from a TDD Practitioner (NDC Oslo)
Dennis Doomen
 
Salesforce Experience Cloud Consulting.pdf
Salesforce Experience Cloud Consulting.pdfSalesforce Experience Cloud Consulting.pdf
Salesforce Experience Cloud Consulting.pdf
VALiNTRY360
 
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdfBoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
Ortus Solutions, Corp
 
Portland Marketo User Group: MOPs & AI - Jeff Canada - May 2025
Portland Marketo User Group: MOPs & AI - Jeff Canada - May 2025Portland Marketo User Group: MOPs & AI - Jeff Canada - May 2025
Portland Marketo User Group: MOPs & AI - Jeff Canada - May 2025
BradBedford3
 
20200823-Intro-to-FIRRTLllllllllllllllllll
20200823-Intro-to-FIRRTLllllllllllllllllll20200823-Intro-to-FIRRTLllllllllllllllllll
20200823-Intro-to-FIRRTLllllllllllllllllll
JonathanSong28
 
Advance Sales Commission Payments in Odoo
Advance Sales Commission Payments in OdooAdvance Sales Commission Payments in Odoo
Advance Sales Commission Payments in Odoo
AxisTechnolabs
 
Optimising Claims Management with Claims Processing Systems
Optimising Claims Management with Claims Processing SystemsOptimising Claims Management with Claims Processing Systems
Optimising Claims Management with Claims Processing Systems
Insurance Tech Services
 
BIS Safety Software Canada - EHS SOFTWARE
BIS Safety Software Canada - EHS SOFTWAREBIS Safety Software Canada - EHS SOFTWARE
BIS Safety Software Canada - EHS SOFTWARE
BIS Safety
 
Field service report Luzon.pptxxxxxxxxxxxxxxxx
Field service report Luzon.pptxxxxxxxxxxxxxxxxField service report Luzon.pptxxxxxxxxxxxxxxxx
Field service report Luzon.pptxxxxxxxxxxxxxxxx
kashinathgpsgc
 
Skilling up your dev team - 8 things to consider when skilling-up your dev team
Skilling up your dev team - 8 things to consider when skilling-up your dev teamSkilling up your dev team - 8 things to consider when skilling-up your dev team
Skilling up your dev team - 8 things to consider when skilling-up your dev team
Derk-Jan de Grood
 
Progecad 2025 Professional Cracked [Latest]
Progecad 2025 Professional Cracked [Latest]Progecad 2025 Professional Cracked [Latest]
Progecad 2025 Professional Cracked [Latest]
Luisa Weist
 
arvr & metaverse development services.pdf
arvr & metaverse development services.pdfarvr & metaverse development services.pdf
arvr & metaverse development services.pdf
marketing810348
 
Shortcomings of EHS Software – And How to Overcome Them
Shortcomings of EHS Software – And How to Overcome ThemShortcomings of EHS Software – And How to Overcome Them
Shortcomings of EHS Software – And How to Overcome Them
TECH EHS Solution
 
Frontier AI Regulation: What form should it take?
Frontier AI Regulation: What form should it take?Frontier AI Regulation: What form should it take?
Frontier AI Regulation: What form should it take?
Petar Radanliev
 
CFCamp2025 - Keynote Day 1 led by Luis Majano.pdf
CFCamp2025 - Keynote Day 1 led by Luis Majano.pdfCFCamp2025 - Keynote Day 1 led by Luis Majano.pdf
CFCamp2025 - Keynote Day 1 led by Luis Majano.pdf
Ortus Solutions, Corp
 
How OnePlan & Microsoft 365 Ensure Strategic Alignment with AI-Powered Portfo...
How OnePlan & Microsoft 365 Ensure Strategic Alignment with AI-Powered Portfo...How OnePlan & Microsoft 365 Ensure Strategic Alignment with AI-Powered Portfo...
How OnePlan & Microsoft 365 Ensure Strategic Alignment with AI-Powered Portfo...
OnePlan Solutions
 
What's-New-with-BoxLang-Brad Wood.pptx.pdf
What's-New-with-BoxLang-Brad Wood.pptx.pdfWhat's-New-with-BoxLang-Brad Wood.pptx.pdf
What's-New-with-BoxLang-Brad Wood.pptx.pdf
Ortus Solutions, Corp
 
Getting Started with BoxLang - CFCamp 2025.pdf
Getting Started with BoxLang - CFCamp 2025.pdfGetting Started with BoxLang - CFCamp 2025.pdf
Getting Started with BoxLang - CFCamp 2025.pdf
Ortus Solutions, Corp
 
Daily Agile Snippets That Boost Team Focus and Flexibility
Daily Agile Snippets That Boost Team Focus and FlexibilityDaily Agile Snippets That Boost Team Focus and Flexibility
Daily Agile Snippets That Boost Team Focus and Flexibility
Orangescrum
 
Why-Choose-an-Authorised-Microsoft-Reseller.pptx
Why-Choose-an-Authorised-Microsoft-Reseller.pptxWhy-Choose-an-Authorised-Microsoft-Reseller.pptx
Why-Choose-an-Authorised-Microsoft-Reseller.pptx
Michael cole
 
15 Years of Insights from a TDD Practitioner (NDC Oslo)
15 Years of Insights from a TDD Practitioner (NDC Oslo)15 Years of Insights from a TDD Practitioner (NDC Oslo)
15 Years of Insights from a TDD Practitioner (NDC Oslo)
Dennis Doomen
 
Salesforce Experience Cloud Consulting.pdf
Salesforce Experience Cloud Consulting.pdfSalesforce Experience Cloud Consulting.pdf
Salesforce Experience Cloud Consulting.pdf
VALiNTRY360
 
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdfBoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
Ortus Solutions, Corp
 
Portland Marketo User Group: MOPs & AI - Jeff Canada - May 2025
Portland Marketo User Group: MOPs & AI - Jeff Canada - May 2025Portland Marketo User Group: MOPs & AI - Jeff Canada - May 2025
Portland Marketo User Group: MOPs & AI - Jeff Canada - May 2025
BradBedford3
 
20200823-Intro-to-FIRRTLllllllllllllllllll
20200823-Intro-to-FIRRTLllllllllllllllllll20200823-Intro-to-FIRRTLllllllllllllllllll
20200823-Intro-to-FIRRTLllllllllllllllllll
JonathanSong28
 

Ten common mistakes made in Function Java - iSense Java Summit

  • 1. Ten common mistakes made with Function Java Brian Vermeer (@BrianVerm)Java Summit
  • 6. Doing too much in a single lambda
  • 7. Lambda Expression In computer programming, a lambda expression is a function definition that is not bound to an identifier. Anonymous functions are often:[1] • arguments being passed to higher-order functions, or • used for constructing the result of a higher-order function that needs to return a function.
  • 8. Lambda in Java Anonymous Inner functions Satisfy a Functional Interface They only exist in runtime Single Line <input> -> <output> or Block <input> -> { function body }
  • 9. Example public void execute() { Beer grolsch = new Beer("Grolsche", 4.3); String result = handleBeer(grolsch, beer -> grolsch.getName() + "-" + grolsch.getAlcohol()); System.out.println(result); } private String handleBeer(Beer beer, Function<Beer, String> func) { System.out.println("handling beer " + beer.getName()); return func.apply(beer); } //Output : Grolsche-4.3
  • 10. 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; }
  • 11. Transform to a methode private String createFullName (Beer 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; } handleBeer(grolsch, this::createFullName);
  • 13. A stream is NOT a data structure
  • 14. A stream is NOT a data structure A stream is NOT a data structure
  • 15. What is Stream ( in Java) Flow of data derived from a Collection Can create a pipeline of function that can be evaluated Intermediate result Lazy evaluated by nature Can transform data, cannot mutate data
  • 16. JAVA 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
  • 17. 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
  • 18. public Stream<Beer> getMeMyBeers() public void execute() { getMeMyBeers() //don’t know if it is consumed yet!!!! … } Don’t return a Stream
  • 19. Not Consuming a Stream
  • 24. List<Beer> beers = List.of(new Beer("Heineken", 5.2), new Beer("Delirium Tremens", 9.0), new Beer("Amstel", 5.1)); beers.stream()
 .limit(10)
 .map(i -> i.getAlcohol())
 .peek(i -> {
 if (i > 7.0)
 throw new RuntimeException();
 }); Consume the stream
  • 26. List<Beer> beers = List.of(new Beer("Heineken", 5.2), new Beer("Delirium Tremens", 9.0), new Beer("Amstel", 5.1)); beers.stream()
 .limit(10)
 .map(i -> i.getAlcohol())
 .peek(i -> {
 if (i > 7.0)
 throw new RuntimeException();
 }) .forEach(System.out::println); Consume the stream 5.2 Exception in thread "main" java.lang.RuntimeException
  • 28. Functional Programming In computer science, functional programming is a programming paradigma style of building the structure and elements of computer programs that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It is a declarative programming paradigm, which means programming is done with expressions or declarations instead of statements. — wikipedia
  • 30. – Kevlin Henney “Asking a question should not change the answer, nor should asking it twice”
  • 31. Immutable objects Less moving parts Easier to reason about code No need to keep a mental map of the state an object is in.
  • 32. Stream cannot mutate private final List<Beer> beers = List.of(new Beer("Heineken", 5.2), new Beer("Amstel", 5.1)); public void execute() { List<Beer> beersNew = beers.stream() .map(beer -> beer.setName(“foo”)) //not allowed .collect(Collectors.toList()); }
  • 33. Stream should not mutate ! private class Beer { String name; Double alcohol; public Beer setName(String name){ this.name = name; return this; } } private final List<Beer> beers = List.of(new Beer("Heineken", 5.2), new Beer("Amstel", 5.1)); public void execute() { List<Beer> beersNew = beers.stream() .map(beer -> beer.setName("foo")) .collect(Collectors.toList()); System.out.println(beers); System.out.println(beersNew); }
  • 34. Stream should not mutate ! private class Beer { String name; Double alcohol; public Beer setName(String name){ this.name = name; return this; } } private final List<Beer> beers = List.of(new Beer("Heineken", 5.2), new Beer("Amstel", 5.1)); public void execute() { List<Beer> beersNew = beers.stream() .map(beer -> beer.setName("foo")) .collect(Collectors.toList()); System.out.println(beers); System.out.println(beersNew); }
  • 35. Return a new copy private class Beer { String name; Double alcohol; public Beer withName(String name){ return new Beer(name, this.alcohol); } } private final List<Beer> beers = List.of(new Beer("Heineken", 5.2), new Beer("Amstel", 5.1)); public void execute() { List<Beer> beersNew = beers.stream() .map(beer -> beer.withName("foo")) .collect(Collectors.toList()); System.out.println(beers); System.out.println(beersNew); }
  • 37. forEach() Terminal functional on a stream. Takes a consumer. Can be used to apply side effects. for-loop without the external iterator
  • 38. simple forEach example List<String> names = List.of("James", "Trisha", "Joshua", "Jessica","Simon", “Heather"); names.stream() .map(String::toUpperCase) .forEach(System.out::println);
  • 39. mutation with forEach List<Beer> beers = List.of(new Beer("Heineken", 5.2), new Beer("Amstel", 5.1)); beers.stream() .forEach(beer -> beer.setAlcohol(0.0));
  • 40. overusing forEach private class Beer { String name; Double alcohol; List<String> reviews; Integer rating; } List<Beer> beers = List.of(new Beer("Heineken", 5.2), new Beer("Amstel", 5.1)); //enrich with ratings beers.stream().forEach(beer -> beer.setRating(findRating(beer.getName()))); //enrich with reviews beers.stream().forEach(beer -> beer.setReviews(findReviews(beer.getName()))); …
  • 42. Assignment Beers -> Brewer -> Country I want the first 3 unique brewers countries from the beer library as comma separated String beerLib.stream() .map(Beer::getBrewer) .distinct() .limit(3) .map(Brewer::getCountry) .map(String::toUpperCase) .collect(Collectors.joining(“,”));
  • 43. Assignment Beers -> Brewer -> Country I want the first 3 unique brewers countries from the beer library as comma separated String beerLib.stream() .map(Beer::getBrewer) .distinct() .limit(3) .map(Brewer::getCountry) .map(String::toUpperCase) .collect(Collectors.joining(“,”)); // wrong
  • 44. Assignment Beers -> Brewer -> Country I want the first 3 unique brewers countries from the beer library as comma separated String beerLib.stream() .map(Beer::getBrewer) .map(Brewer::getCountry) .map(String::toUpperCase) .distinct() .limit(3) .collect(Collectors.joining(“,”)); // correct
  • 45. Infinite stream IntStream.iterate(0, i -> ( i + 1) % 2)
 .distinct()
 .limit(10)
 .forEach(i -> System.out.println(i));
  • 46. Infinite stream IntStream.iterate(0, i -> ( i + 1) % 2)
 .distinct()
 .limit(10)
 .forEach(i -> System.out.println(i));
 // will run forever IntStream.iterate(0, i -> ( i + 1) % 2)
 .limit(10)
 .distinct()
 .forEach(i -> System.out.println(i)); //will terminate
  • 47. Infinite stream IntStream.iterate(0, i -> ( i + 1) % 2)
 .parallel() .distinct()
 .limit(10)
 .forEach(i -> System.out.println(i));
 // will run forever on all threads.
  • 48. Solution 1. Look closely at the order of operations
 - prevent incorrect answers
 
 2. Only use infinite streams when absolutely necessary. rather use: 
 IntStream.range(0,10); IntStream.rangeClosed(0,10); IntStream.iterate(0, i -> i < 10, i -> i + 1); //java 9 and up
  • 50. Optional Java’s implementation of the Maybe Monad Encapsulation to handle possible null value Consider it a wrapper where a value can be absent Force the user to unpack the Optional before using it.
  • 51. Optional Optional<String> c = null //please avoid this
  • 52. public void execute() { Optional<String> maybeString = getText(); String unpacked = maybeString.get(); } Unpack Optional
  • 53. public void execute() { Optional<String> maybeString = getText(); String unpacked = maybeString.get(); } Unpack Optional NoSuchElementException
  • 54. public void execute() { Optional<String> maybeString = getText(); String unpacked = maybeString.get(); } Unpack Optional public void execute() { Optional<String> maybeString = getText(); if (maybeString.isPresent()) { String unpacked = maybeString.get(); } } NoSuchElementException
  • 55. Unpack Optional public void execute() { Optional<String> maybeString = getText(); maybeString.ifPresent( str -> /* doSomething */ ); } public void execute() { Optional<String> maybeString = getText(); maybeString.map(str -> str + “."); }
  • 57. Alternative flow - orElse() - orElseGet() - orElseThrow()
  • 58. orElseThrow public void execute() {
 Optional<String> maybeString = Optional.empty();
 maybeString
 .map(this::runIfExist)
 .orElseThrow(() -> new RuntimeException("Optional was empty"));
 }
  • 59. orElse public void execute() {
 Optional<String> maybeString = Optional.of("foo");
 String newString = maybeString
 .map(this::runIfExist)
 .orElse(runIfEmpty());
 System.out.println(newString);
 }
 private String runIfExist(String str) {
 System.out.println("only run if optional is filled ");
 return str;
 }
 private String runIfEmpty() {
 System.out.println("only run if empty");
 return "empty";
 }
  • 60. orElse public void execute() {
 Optional<String> maybeString = Optional.of("foo");
 String newString = maybeString
 .map(this::runIfExist)
 .orElse(runIfEmpty());
 System.out.println(newString);
 }
 private String runIfExist(String str) {
 System.out.println("only run if optional is filled ");
 return str;
 }
 private String runIfEmpty() {
 System.out.println("only run if empty");
 return "empty";
 } only run if optional is filled only run if empty foo
  • 61. orElseGet public void execute() {
 Optional<String> maybeString = Optional.of("foo");
 String newString = maybeString
 .map(this::runIfExist)
 .orElseGet(() -> runIfEmpty());
 System.out.println(newString);
 }
 private String runIfExist(String str) {
 System.out.println("only run if optional is filled ");
 return str;
 }
 private String runIfEmpty() {
 System.out.println("only run if empty");
 return "empty";
 }
  • 62. orElseGet public void execute() {
 Optional<String> maybeString = Optional.of("foo");
 String newString = maybeString
 .map(this::runIfExist)
 .orElseGet(() -> runIfEmpty());
 System.out.println(newString);
 }
 private String runIfExist(String str) {
 System.out.println("only run if optional is filled ");
 return str;
 }
 private String runIfEmpty() {
 System.out.println("only run if empty");
 return "empty";
 } only run if optional is filled foo
  • 63. what else? - When using orElse(x), make sure x doesn’t contain any side effects - Only use orElse() to assign a default value - Use orElseGet() to run an alternative flow
  • 65. Checked Exceptions & Lambda public Beer doSomething(Beer beer) throws IsEmptyException { …} Function <Beer,Beer> fBeer = beer -> doSomething(beer) 

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

  • 67. Checked Exceptions & Lambda public Beer doSomething(Beer beer) throws IsEmptyException { …} beerLib.stream() .map(beer -> {
 try{
 return doSomething(beer);
 } catch (IsEmptyException e) {
 throw new RuntimeException(e);
 }
 };) .collect(Collectors.toList()); //not very pretty
  • 68. 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);
 }
 } beerLib.stream() .map(this::wrappedDoSomeThing) .collect(Collectors.toList());
  • 69. 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);
 }
 };
 }; beerLib.stream() .map(beer -> wrap(doSomething(beer))) .collect(Collectors.toList());
  • 70. Either type public class Either<L, R> { private final L left; private final R right; private Either(L left, R right) { this.left = left; this.right = right; } public static <L,R> Either<L,R> Left( L value) { return new Either(value, null); } public static <L,R> Either<L,R> Right( R value) { return new Either(null, value); } … }
  • 71. Either type private Either<Exception, String> canGoWrong(Integer input) { if (input > 10) { return Either.Left(new RuntimeException("larger then 10")); } return Either.Right("["+input+"]"); } List<Either<Exception, String>> canGoWrongs = IntStream.range(0,12) .mapToObj(i -> canGoWrong(i)) .collect(Collectors.toList());
  • 72. Either type private Either<Exception, String> canGoWrong(Integer input) { if (input > 10) { return Either.Left(new RuntimeException("larger then 10")); } return Either.Right(“["+input+"]"); } List<Either<Exception, String>> canGoWrongs = IntStream.range(0,12) .mapToObj(i -> canGoWrong(i)) .collect(Collectors.toList()); canGoWrongs.stream() .map(e -> e.mapRight(s -> s.toUpperCase())) .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)) .forEach(System.out::println);
  • 74. //java 9 List myList = List.of(1,2,3,4,5) //pre Java9 List myList = Arrays.asList(new String[] {“a”,"b","c"}); Creating collections
  • 75. //java 9 List myList = List.of(1,2,3,4,5) //pre Java9 List myList = Arrays.asList(new String[] {"a","b","c"}); // since Java 8 List myList = Stream.of("a","b","c","d").collect(Collectors.toList()); Creating collections
  • 76. private Beer foo(){...} private Beer bar(){...} private Beer fooBar(){…} Beer myBeer = new Beer(); Beer result = fooBar(bar(foo(myBeer))); Using Stream.of
  • 77. private Beer foo(){...} private Beer bar(){...} private Beer fooBar(){…} Beer myBeer = new Beer(); Beer result = fooBar(bar(foo(myBeer))); Using Stream.of Beer result = Stream.of(myBeer) .map(this::foo)
 .map(this::bar)
 .map(this::fooBar)
 .findFirst().get();
  • 78. String sentence = "The quick fox jumps over the lazy dog. "; String[] words = sentence .trim() .toUpperCase() .split(" "); for(String word : words) { System.out.println(word); } Using Stream.of
  • 79. String sentence = "The quick fox jumps over the lazy dog. "; String[] words = sentence .trim() .toUpperCase() .split(" "); for(String word : words) { System.out.println(word); } Stream.of(sentence) .map(String::trim) .map(String::toUpperCase) .map(str -> str.split(" ")) .flatMap(array -> Arrays.stream(array)) .forEach(System.out::println); Using Stream.of