SlideShare une entreprise Scribd logo
1  sur  81
Télécharger pour lire hors ligne
JAVA 8
NEW FEATURES
or the ones you might actually use
Sharon Rozinsky
18/3/2014Release Date
Java 8 adoption is running
six months ahead of the
original predictions
http://www.baeldung.com/java-8-adoption-march-2016
1.
Lambda Expressions
Encapsulate a functionality and pass it as an argument
Replace the cumbersome syntax of anonymous functions
Let’s try an example - write a code to search a list of
people by a certain criteria
Attempt
#
1
Attempt
#
2
Attempt
#
3
public static void printPeopleWithinAgeRange(
List<Person> people, int low, int high) {
for (Person p : people) {
if (low <= p.getAge() && p.getAge() < high) {
p.printPerson();
}
}
}
But what if the search criteria changes?
Attempt
#
1
Attempt
#
2
Attempt
#
3
public static void printPeople(List<Person> people,
CheckPerson tester) {
for (Person p : people) {
if (tester.test(p)) {
p.printPerson();
}
}
}
printPeople(
people,
new CheckPerson() {
public boolean test(Person p) {
return p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25;
}
}
);
Okay - let’s try it with lambda’s
Attempt
#
1
Attempt
#
2
Attempt
#
3
printPeople(
people,
(Person p) -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25
);
CheckPerson must be a functional interface!
Syntax Rules
Basic
(p1, p2, …) -> {statements}
Syntax Rules
Evaluate And Return
p -> p.getAge() > 25
Syntax Rules
Multiple Statements
p -> {
int x = 25;
return p > x;
}
Method References
Use lambda expressions to reference methods.
There are 4 kinds of method references:
Method References
Arrays.sort(stringArray, String::compareToIgnoreCase);
==
Arrays.sort(stringArray, (String a, String b) ->
a.compareToIgnoreCase(b));
2.
Functional Interfaces
An interface with only one abstract method.
(possible to have more non abstract methods
using default).
Not a new concept:
Runnable, Callable, Comparator etc...
We saw that we can create instances of functional
interfaces using lambdas.
*Remember the CheckPerson interface from the first example.
@FunctionalInterface
(not a must if demands are met = only 1 method)
The java.util.function package contains many built in functional
interfaces:
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
Predicate<Person> canDrive = p -> p.getAge() > 16;
The java.util.function package contains many built in functional
interfaces:
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
Function<String, Integer> intToString = x ->
Integer.valueOf(x);
3.
Default Methods
Add functionality to interfaces without breaking
backward compatibility.
New keyword: default
Enables method implementation in interfaces
Side effect of Oracle’s extensions to the collection
interfaces.
Example
public interface Person {
void goSomewhere(Location location);
}
public Class NicePerson implements Person{
public void goSomewhere(Location location) {
…
}
}
Now Let’s add a method to the Person interface -
void saySomething (String whatToSay)
public interface Person {
void goSomewhere(Location location);
default void saySomething (String whatToSay) {
…
Sysout.println(whatToSay);
}
}
Adding a default method to an interface requires
no additions to the implementing classes.
Like any other method in the interface default
methods are implicitly public
Extending an interface with a default method:
Default method is not mentioned - extended
interface gets the default method.
Extending an interface with a default method:
Redeclaring the default method - method
becomes abstract (and implementing class has to
implement it).
Extending an interface with a default method:
Redefine the default method - override the
method functionality.
Any Famous Problem You Can Think Of?
Diamond Problem
interface InterfaceA {
default public void sayHi() {
System.out.println("Hi from InterfaceA");
}
}
interface InterfaceB {
default public void sayHi() {
System.out.println("Hi from InterfaceB");
}
}
public class MyClass implements InterfaceA, InterfaceB {
public static void main(String[] args) {
...
}
}
interface InterfaceA {
default public void sayHi() {
System.out.println("Hi from InterfaceA");
}
}
interface InterfaceB {
default public void sayHi() {
System.out.println("Hi from InterfaceB");
}
}
public class MyClass implements InterfaceA, InterfaceB {
public static void main(String[] args) {
...
}
}
Compilation
Error!
Solution:
- Provide implementation to sayHi in MyClass
- Can use: InterfaceA.super.sayHi()
Default methods are never final
Default methods cannot be synchronized
Default methods are always public
There are no fields in an interface - hard to maintain a state
For most cases - classes define what an object is while an interface
defines what an object can do
Interfaces vs. Abstract Classes
4.
Streams
A new Java API that helps processing data and
collections in a declarative way.
Formal definition: “A sequence of elements
supporting sequential and parallel aggregate
operations.”
The Pipeline Approach
Java streams use a pipeline approach to perform the different tasks
needed to process a given collection.
A pipeline is composed of the following:
Source - any structure that holds data: array,
collection, I/O channel, generator functions, etc…
A pipeline is composed of the following:
Intermediate operations - 0 or more operations
that produce a new stream. The basic examples
for this are the Stream() and Filter() operations.
A pipeline is composed of the following:
Terminal operation - an operation that returns a
non stream value e.g. primitives, collections or no
value at all.
Example
double average = people
.stream()
.filter(p -> p.getGender() == Person.Sex.MALE)
.mapToInt(Person::getAge)
.average()
.getAsDouble();
Produce a stream from the given collection
double average = people
.stream()
.filter(p -> p.getGender() == Person.Sex.MALE)
.mapToInt(Person::getAge)
.average()
.getAsDouble();
Filter on a predicate - produces another
stream
double average = people
.stream()
.filter(p -> p.getGender() == Person.Sex.MALE)
.mapToInt(Person::getAge)
.average()
.getAsDouble();
Map only the age of each person - return a
stream of type IntStream
double average = people
.stream()
.filter(p -> p.getGender() == Person.Sex.MALE)
.mapToInt(Person::getAge)
.average()
.getAsDouble();
Perform average on all values - returns an
OptionalDouble
double average = people
.stream()
.filter(p -> p.getGender() == Person.Sex.MALE)
.mapToInt(Person::getAge)
.average()
.getAsDouble();
Return the final value
int numberOfMales = 0;
int totalAge = 0;
foreach(person p : people){
if(p.getGender() == Person.Sex.MALE){
numberOfMales++;
totalAge += p.getAge();
}
}
if(numberOfMales > 0){
return totalAge / numberOfMales;
}
Old School Way:
Reduce
The average() operation from the previous example is one of
many reduction methods (the terminal operations)
The Java 8 API provides handy reduction operations but also a
more generic method to perform reduction by yourself
double agesSum = people
.stream()
.filter(p -> p.getGender() == Person.Sex.MALE)
.mapToInt(Person::getAge)
.reduce(0, (a,b) -> a + b)
Identity - an initial and
also default value if the
stream is empty.
Accumulator - an
associative function
reduce also has a 3 parameter version that
accepts an identity, a mapper which replaces the
mapToInt in this case and a combiner function
that serves as an accumulator
Collect
The reduce method creates a new value for every element that it
processes.
The collect method modifies an existing value.
Think about creating the average ages in the last example (Yap it’s hard
with reduce…).
Let’s try it with collect:
Before we begin:
IntCosumer - a built in functional interface that accepts an int and
returns no result.
Defines a method called accept.
class Averager implements IntConsumer
{
private int total = 0;
private int count = 0;
public double average() {
return count > 0 ? ((double) total)/count : 0;
}
public void accept(int i) { total += i; count++; }
public void combine(Averager other) {
total += other.total;
count += other.count;
}
}
Averager averageCollect = people
.stream()
.filter(p -> p.getGender() == Person.Sex.MALE)
.map(Person::getAge)
.collect(Averager::new, Averager::accept,
Averager::combine);
System.out.println("Average age of male members: " +
averageCollect.average());
Supplier - a factory function to
create new instances of the
result type
Accumulator - a function that
modifies the result container
Combiner - a function that
takes two result objects and
merges them into one
combined result
For most use cases we would probably want to
just run simple operations on a stream and get
some collection back as a result.
For this we can use Collectors:
List<String> namesOfMaleMembersCollect = people
.stream()
.filter(p -> p.getGender() == Person.Sex.MALE)
.map(p -> p.getName())
.collect(Collectors.toList());
Map<Person.Sex, List<Person>> byGender = people
.stream()
.collect(
Collectors.groupingBy(Person::getGender));
5.
More Additions
Parallel Streams
Java streams also support parallel computation via parallelStream().
Just call it instead of stream() and the stream would be divided into
substreams and processed in a parallel manner.
This doesn’t guarantee faster execution times and really depends on
the hardware and application.
A big topic for another talk.
String.Join
String message = String.join(“-”, “Java”, “8”, “talk”);
Returns “java-8-talk”
Optional
A new object wrapper that helps handling null pointer exceptions
Essentially wraps any object and exposes methods to make the object
handle NULL cases
Optional
Initializing:
Optional<MyObject> myObject = Optional.empty();
Or
MyObject nonNullObject = new MyObject();
Optional<MyObject> myObject = Optional.of(nonNullObject);
Optional
Perform action if the object is not null:
myObject.ifPresent(System.out::println)
Optional
Only check if the object is null or not
myObject.isPresent()
Optional
Replace the ternary (? :) operator
MyObject newOne = myObject.orElse
(new MyObject());
Optional
The Optional class contains methods similar to streams:
filter, map etc. They can be used to achieve similar
behavior to streams.
New DateTime API
But read this if it’s relevant: https://dzone.com/articles/introducing-new-date-and-time
More Stuff
- Additions to concurrency API’s - For another talk.
- IntelliJ suggestions are now Java 8 Ready - USE THEM!!!
- Samples in these slides are based on:
http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html
- Great code samples for Java 8 - https://github.com/java8/Java8InAction
- Great article about streams -
http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-
2177646.html
thanks!
Any questions?
@sharon_roz
Credits
Special thanks to all the people who made and released
these awesome resources for free:
Presentation template by SlidesCarnival
Photographs by Unsplash

Contenu connexe

Tendances

Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language EnhancementsYuriy Bondaruk
 
Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams IndicThreads
 
Java 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven editionJava 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven editionJosé Paumard
 
SeaJUG March 2004 - Groovy
SeaJUG March 2004 - GroovySeaJUG March 2004 - Groovy
SeaJUG March 2004 - GroovyTed Leung
 
Functional programming basics
Functional programming basicsFunctional programming basics
Functional programming basicsopenbala
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present FutureIndicThreads
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional ProgrammingDmitry Buzdin
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummiesknutmork
 
Java 8 - project lambda
Java 8 - project lambdaJava 8 - project lambda
Java 8 - project lambdaIvar Østhus
 
Functional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsFunctional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsCodeOps Technologies LLP
 
Nice to meet Kotlin
Nice to meet KotlinNice to meet Kotlin
Nice to meet KotlinJieyi Wu
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. StreamsDEVTYPE
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Ganesh Samarthyam
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL fileRACHIT_GUPTA
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Calvin Cheng
 

Tendances (20)

Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language Enhancements
 
Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams
 
Java 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven editionJava 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven edition
 
SeaJUG March 2004 - Groovy
SeaJUG March 2004 - GroovySeaJUG March 2004 - Groovy
SeaJUG March 2004 - Groovy
 
Functional programming basics
Functional programming basicsFunctional programming basics
Functional programming basics
 
Java data types
Java data typesJava data types
Java data types
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
Core Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug HuntCore Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug Hunt
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional Programming
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 
Java 8 - project lambda
Java 8 - project lambdaJava 8 - project lambda
Java 8 - project lambda
 
Functional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsFunctional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and Streams
 
Nice to meet Kotlin
Nice to meet KotlinNice to meet Kotlin
Nice to meet Kotlin
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
 
What are arrays in java script
What are arrays in java scriptWhat are arrays in java script
What are arrays in java script
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
 

En vedette

Down-to-Earth Microservices with Java EE
Down-to-Earth Microservices with Java EEDown-to-Earth Microservices with Java EE
Down-to-Earth Microservices with Java EEReza Rahman
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheLeslie Samuel
 
Byte array to hex string transformer
Byte array to hex string transformerByte array to hex string transformer
Byte array to hex string transformerRahul Kumar
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing웅식 전
 
Design, Simulation and Verification of Generalized Photovoltaic cells Model U...
Design, Simulation and Verification of Generalized Photovoltaic cells Model U...Design, Simulation and Verification of Generalized Photovoltaic cells Model U...
Design, Simulation and Verification of Generalized Photovoltaic cells Model U...IDES Editor
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arraysphanleson
 
TypeScript by Howard
TypeScript by HowardTypeScript by Howard
TypeScript by HowardLearningTech
 
Multi string PV array
Multi string PV arrayMulti string PV array
Multi string PV arrayNIT MEGHALAYA
 
Groovy Powered Clean Code
Groovy Powered Clean CodeGroovy Powered Clean Code
Groovy Powered Clean CodeGR8Conf
 
Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with GroovyGR8Conf
 
Groovy in the Cloud
Groovy in the CloudGroovy in the Cloud
Groovy in the CloudDaniel Woods
 
Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with GroovyAli Tanwir
 
Advanced API Design: how an awesome API can help you make friends, get rich, ...
Advanced API Design: how an awesome API can help you make friends, get rich, ...Advanced API Design: how an awesome API can help you make friends, get rich, ...
Advanced API Design: how an awesome API can help you make friends, get rich, ...Jonathan Dahl
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvmArnaud Giuliani
 
Spring one 2012 Groovy as a weapon of maas PaaSification
Spring one 2012 Groovy as a weapon of maas PaaSificationSpring one 2012 Groovy as a weapon of maas PaaSification
Spring one 2012 Groovy as a weapon of maas PaaSificationNenad Bogojevic
 

En vedette (20)

Down-to-Earth Microservices with Java EE
Down-to-Earth Microservices with Java EEDown-to-Earth Microservices with Java EE
Down-to-Earth Microservices with Java EE
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
 
Java SE 8
Java SE 8Java SE 8
Java SE 8
 
Byte array to hex string transformer
Byte array to hex string transformerByte array to hex string transformer
Byte array to hex string transformer
 
array
array array
array
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
 
Design, Simulation and Verification of Generalized Photovoltaic cells Model U...
Design, Simulation and Verification of Generalized Photovoltaic cells Model U...Design, Simulation and Verification of Generalized Photovoltaic cells Model U...
Design, Simulation and Verification of Generalized Photovoltaic cells Model U...
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
 
TypeScript by Howard
TypeScript by HowardTypeScript by Howard
TypeScript by Howard
 
Multi string PV array
Multi string PV arrayMulti string PV array
Multi string PV array
 
Groovy Powered Clean Code
Groovy Powered Clean CodeGroovy Powered Clean Code
Groovy Powered Clean Code
 
Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with Groovy
 
Groovy on Android
Groovy on AndroidGroovy on Android
Groovy on Android
 
Groovy in the Cloud
Groovy in the CloudGroovy in the Cloud
Groovy in the Cloud
 
Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with Groovy
 
Advanced API Design: how an awesome API can help you make friends, get rich, ...
Advanced API Design: how an awesome API can help you make friends, get rich, ...Advanced API Design: how an awesome API can help you make friends, get rich, ...
Advanced API Design: how an awesome API can help you make friends, get rich, ...
 
Ci for-android-apps
Ci for-android-appsCi for-android-apps
Ci for-android-apps
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
Spring one 2012 Groovy as a weapon of maas PaaSification
Spring one 2012 Groovy as a weapon of maas PaaSificationSpring one 2012 Groovy as a weapon of maas PaaSification
Spring one 2012 Groovy as a weapon of maas PaaSification
 

Similaire à Java 8 new features or the ones you might actually use

FUNctional Programming in Java 8
FUNctional Programming in Java 8FUNctional Programming in Java 8
FUNctional Programming in Java 8Richard Walker
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesGanesh Samarthyam
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In JavaAndrei Solntsev
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...Akaks
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
 
JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJosé Paumard
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Codemotion
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
 

Similaire à Java 8 new features or the ones you might actually use (20)

Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
FUNctional Programming in Java 8
FUNctional Programming in Java 8FUNctional Programming in Java 8
FUNctional Programming in Java 8
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In Java
 
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
 
Java 8 by example!
Java 8 by example!Java 8 by example!
Java 8 by example!
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easy
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018
 
Lazy java
Lazy javaLazy java
Lazy java
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 

Dernier

%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 Stilfonteinmasabamasaba
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
%+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
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durbanmasabamasaba
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
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 SoftwareJim McKeeth
 
%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 tembisamasabamasaba
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsBert Jan Schrijver
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
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 pastPapp Krisztián
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
%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 masabamasaba
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
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 AidPhilip Schwarz
 
%+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
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburgmasabamasaba
 

Dernier (20)

%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
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
%+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 Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
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
 
%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
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
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
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%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
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
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...
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 

Java 8 new features or the ones you might actually use

  • 1. JAVA 8 NEW FEATURES or the ones you might actually use Sharon Rozinsky
  • 2. 18/3/2014Release Date Java 8 adoption is running six months ahead of the original predictions http://www.baeldung.com/java-8-adoption-march-2016
  • 3.
  • 5. Encapsulate a functionality and pass it as an argument Replace the cumbersome syntax of anonymous functions
  • 6. Let’s try an example - write a code to search a list of people by a certain criteria Attempt # 1 Attempt # 2 Attempt # 3
  • 7. public static void printPeopleWithinAgeRange( List<Person> people, int low, int high) { for (Person p : people) { if (low <= p.getAge() && p.getAge() < high) { p.printPerson(); } } }
  • 8. But what if the search criteria changes? Attempt # 1 Attempt # 2 Attempt # 3
  • 9. public static void printPeople(List<Person> people, CheckPerson tester) { for (Person p : people) { if (tester.test(p)) { p.printPerson(); } } }
  • 10. printPeople( people, new CheckPerson() { public boolean test(Person p) { return p.getGender() == Person.Sex.MALE && p.getAge() >= 18 && p.getAge() <= 25; } } );
  • 11. Okay - let’s try it with lambda’s Attempt # 1 Attempt # 2 Attempt # 3
  • 12. printPeople( people, (Person p) -> p.getGender() == Person.Sex.MALE && p.getAge() >= 18 && p.getAge() <= 25 );
  • 13. CheckPerson must be a functional interface!
  • 14. Syntax Rules Basic (p1, p2, …) -> {statements}
  • 15. Syntax Rules Evaluate And Return p -> p.getAge() > 25
  • 16. Syntax Rules Multiple Statements p -> { int x = 25; return p > x; }
  • 17. Method References Use lambda expressions to reference methods. There are 4 kinds of method references:
  • 20. An interface with only one abstract method. (possible to have more non abstract methods using default).
  • 21. Not a new concept: Runnable, Callable, Comparator etc...
  • 22. We saw that we can create instances of functional interfaces using lambdas. *Remember the CheckPerson interface from the first example.
  • 23. @FunctionalInterface (not a must if demands are met = only 1 method)
  • 24. The java.util.function package contains many built in functional interfaces: @FunctionalInterface public interface Predicate<T> { boolean test(T t); } Predicate<Person> canDrive = p -> p.getAge() > 16;
  • 25. The java.util.function package contains many built in functional interfaces: @FunctionalInterface public interface Function<T, R> { R apply(T t); } Function<String, Integer> intToString = x -> Integer.valueOf(x);
  • 27. Add functionality to interfaces without breaking backward compatibility.
  • 30. Side effect of Oracle’s extensions to the collection interfaces.
  • 32. public interface Person { void goSomewhere(Location location); } public Class NicePerson implements Person{ public void goSomewhere(Location location) { … } }
  • 33. Now Let’s add a method to the Person interface - void saySomething (String whatToSay)
  • 34. public interface Person { void goSomewhere(Location location); default void saySomething (String whatToSay) { … Sysout.println(whatToSay); } }
  • 35. Adding a default method to an interface requires no additions to the implementing classes.
  • 36. Like any other method in the interface default methods are implicitly public
  • 37. Extending an interface with a default method: Default method is not mentioned - extended interface gets the default method.
  • 38. Extending an interface with a default method: Redeclaring the default method - method becomes abstract (and implementing class has to implement it).
  • 39. Extending an interface with a default method: Redefine the default method - override the method functionality.
  • 40. Any Famous Problem You Can Think Of?
  • 42. interface InterfaceA { default public void sayHi() { System.out.println("Hi from InterfaceA"); } } interface InterfaceB { default public void sayHi() { System.out.println("Hi from InterfaceB"); } } public class MyClass implements InterfaceA, InterfaceB { public static void main(String[] args) { ... } }
  • 43. interface InterfaceA { default public void sayHi() { System.out.println("Hi from InterfaceA"); } } interface InterfaceB { default public void sayHi() { System.out.println("Hi from InterfaceB"); } } public class MyClass implements InterfaceA, InterfaceB { public static void main(String[] args) { ... } } Compilation Error!
  • 44. Solution: - Provide implementation to sayHi in MyClass - Can use: InterfaceA.super.sayHi()
  • 45. Default methods are never final Default methods cannot be synchronized Default methods are always public There are no fields in an interface - hard to maintain a state For most cases - classes define what an object is while an interface defines what an object can do Interfaces vs. Abstract Classes
  • 47. A new Java API that helps processing data and collections in a declarative way. Formal definition: “A sequence of elements supporting sequential and parallel aggregate operations.”
  • 48. The Pipeline Approach Java streams use a pipeline approach to perform the different tasks needed to process a given collection.
  • 49. A pipeline is composed of the following: Source - any structure that holds data: array, collection, I/O channel, generator functions, etc…
  • 50. A pipeline is composed of the following: Intermediate operations - 0 or more operations that produce a new stream. The basic examples for this are the Stream() and Filter() operations.
  • 51. A pipeline is composed of the following: Terminal operation - an operation that returns a non stream value e.g. primitives, collections or no value at all.
  • 53. double average = people .stream() .filter(p -> p.getGender() == Person.Sex.MALE) .mapToInt(Person::getAge) .average() .getAsDouble(); Produce a stream from the given collection
  • 54. double average = people .stream() .filter(p -> p.getGender() == Person.Sex.MALE) .mapToInt(Person::getAge) .average() .getAsDouble(); Filter on a predicate - produces another stream
  • 55. double average = people .stream() .filter(p -> p.getGender() == Person.Sex.MALE) .mapToInt(Person::getAge) .average() .getAsDouble(); Map only the age of each person - return a stream of type IntStream
  • 56. double average = people .stream() .filter(p -> p.getGender() == Person.Sex.MALE) .mapToInt(Person::getAge) .average() .getAsDouble(); Perform average on all values - returns an OptionalDouble
  • 57. double average = people .stream() .filter(p -> p.getGender() == Person.Sex.MALE) .mapToInt(Person::getAge) .average() .getAsDouble(); Return the final value
  • 58. int numberOfMales = 0; int totalAge = 0; foreach(person p : people){ if(p.getGender() == Person.Sex.MALE){ numberOfMales++; totalAge += p.getAge(); } } if(numberOfMales > 0){ return totalAge / numberOfMales; } Old School Way:
  • 59. Reduce The average() operation from the previous example is one of many reduction methods (the terminal operations) The Java 8 API provides handy reduction operations but also a more generic method to perform reduction by yourself
  • 60. double agesSum = people .stream() .filter(p -> p.getGender() == Person.Sex.MALE) .mapToInt(Person::getAge) .reduce(0, (a,b) -> a + b) Identity - an initial and also default value if the stream is empty. Accumulator - an associative function
  • 61. reduce also has a 3 parameter version that accepts an identity, a mapper which replaces the mapToInt in this case and a combiner function that serves as an accumulator
  • 62. Collect The reduce method creates a new value for every element that it processes. The collect method modifies an existing value. Think about creating the average ages in the last example (Yap it’s hard with reduce…). Let’s try it with collect:
  • 63. Before we begin: IntCosumer - a built in functional interface that accepts an int and returns no result. Defines a method called accept.
  • 64. class Averager implements IntConsumer { private int total = 0; private int count = 0; public double average() { return count > 0 ? ((double) total)/count : 0; } public void accept(int i) { total += i; count++; } public void combine(Averager other) { total += other.total; count += other.count; } }
  • 65. Averager averageCollect = people .stream() .filter(p -> p.getGender() == Person.Sex.MALE) .map(Person::getAge) .collect(Averager::new, Averager::accept, Averager::combine); System.out.println("Average age of male members: " + averageCollect.average()); Supplier - a factory function to create new instances of the result type Accumulator - a function that modifies the result container Combiner - a function that takes two result objects and merges them into one combined result
  • 66. For most use cases we would probably want to just run simple operations on a stream and get some collection back as a result. For this we can use Collectors:
  • 67. List<String> namesOfMaleMembersCollect = people .stream() .filter(p -> p.getGender() == Person.Sex.MALE) .map(p -> p.getName()) .collect(Collectors.toList()); Map<Person.Sex, List<Person>> byGender = people .stream() .collect( Collectors.groupingBy(Person::getGender));
  • 69. Parallel Streams Java streams also support parallel computation via parallelStream(). Just call it instead of stream() and the stream would be divided into substreams and processed in a parallel manner. This doesn’t guarantee faster execution times and really depends on the hardware and application. A big topic for another talk.
  • 70. String.Join String message = String.join(“-”, “Java”, “8”, “talk”); Returns “java-8-talk”
  • 71. Optional A new object wrapper that helps handling null pointer exceptions Essentially wraps any object and exposes methods to make the object handle NULL cases
  • 72. Optional Initializing: Optional<MyObject> myObject = Optional.empty(); Or MyObject nonNullObject = new MyObject(); Optional<MyObject> myObject = Optional.of(nonNullObject);
  • 73. Optional Perform action if the object is not null: myObject.ifPresent(System.out::println)
  • 74. Optional Only check if the object is null or not myObject.isPresent()
  • 75. Optional Replace the ternary (? :) operator MyObject newOne = myObject.orElse (new MyObject());
  • 76. Optional The Optional class contains methods similar to streams: filter, map etc. They can be used to achieve similar behavior to streams.
  • 78. But read this if it’s relevant: https://dzone.com/articles/introducing-new-date-and-time
  • 79. More Stuff - Additions to concurrency API’s - For another talk. - IntelliJ suggestions are now Java 8 Ready - USE THEM!!! - Samples in these slides are based on: http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html - Great code samples for Java 8 - https://github.com/java8/Java8InAction - Great article about streams - http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams- 2177646.html
  • 81. Credits Special thanks to all the people who made and released these awesome resources for free: Presentation template by SlidesCarnival Photographs by Unsplash