SlideShare una empresa de Scribd logo
1 de 60
Descargar para leer sin conexión
!1
RETURNOF
THE AVA
J
JAVA EIGHT
Java 8 – what’s new?
Lambdas, Extension Methods, SAMs, Streams, Method
Handles, Oh My!
Nashorn JS engine
JSR-310: Date & time API
No more PermGen– where classloaders go to die
...
!2
Java 8 – what’s new?
Lambdas, Extension Methods, SAMs, Streams, Method
Handles, Oh My!
Nashorn JS engine
JSR-310: Date & time API
No more PermGen– where classloaders go to die
...
!3
Your Mission
Should you choose to accept it
Sort a list of people
by their names
Java 7
Collections.sort(people, new Comparator<Person>() {
public int compare(Person x, Person y) {
return x.getName().compareTo(y.getName());
}
});
!5
We are not amused
© Fredrik Vraalsen 2012
Java 8
Comparator<Person> byName = new Comparator<Person>() {
public int compare(Person x, Person y) {
return x.getName().compareTo(y.getName());
}
};
Single Abstract Method
!
(SAM)
!7
Single Abstract Method
Interface with only one (non-default) method
Abstract class with only one abstract method
Sound familiar?
Pretty much every event listener, callback mechanism, ...
Can be replaced by a Lambda
!8
Lambda
Closure
Anonymous function
!9
SAM
Comparator<Person> byName = new Comparator<Person>() {
public int compare(Person x, Person y) {
return x.getName().compareTo(y.getName());
}
};
!10
SAM
Comparator<Person> byName = new Comparator<Person>() {
public int compare(Person x, Person y) {
return x.getName().compareTo(y.getName());
}
};
BodyReturn type
Parameter list
Method name
Type
!11
Lambda
Comparator<Person> byName = new Comparator<Person>() {
public int compare(Person x, Person y) {
return x.getName().compareTo(y.getName());
}
};
BodyReturn type
Parameter list
Method name
Type
!12
Lambda
Comparator<Person> byName =
!
return x.getName().compareTo(y.getName());
};
BodyReturn type?
Parameter list
(Person x, Person y) -> {
!13
Lambda
Comparator<Person> byName =
(Person x, Person y) ->
Parameter list
BodyReturn type?
x.getName().compareTo(y.getName());
{
};
return
!14
Lambda
Comparator<Person> byName =
Parameter list
BodyReturn type?
(x, y) -> x.getName().compareTo(y.getName());(Person x, Person y)
!15
Lambda
Comparator<Person> byName =
(x, y) -> x.getName().compareTo(y.getName());
!
Collections.sort(people, byName);
!16
Lambda
Comparator<Person> byName =
(x, y) -> x.getName().compareTo(y.getName());
!
sort(people, byName);
!17
Lambda
!
!
!
sort(people, (x, y) -> x.getName().compareTo(y.getName()));
!18
Comparators
import static java.util.Comparator.comparing;
…
!
sort(people, comparing((Person p) -> p.getName());
!19
Cool!
!
!
!
!
Now onwards... © Fredrik Vraalsen 2013
Method handles
Reference to methods
Can be used in place of lambdas
!21
Method handles
!
!
!
sort(people, comparing((Person p) -> p.getName()));
!22
Method handles
!
!
!
sort(people, comparing(Person::getName));
!23
Ok, nice...
What else?
© Fredrik Vraalsen 2012
Extension methods
!
!
!
sort(people, comparing(Person::getName));
!25
Extension methods
!
!
!
people.sort(comparing(Person::getName));
!26
Extension methods
!27
java.util.List:
!
default void sort(Comparator<? super E> c)
Extension methods
Defender Method
Default Method
(Virtual) Extension Method
!28
java.util.List:
!
default void sort(Comparator<? super E> c)
Extension methods
java.util.List:
!
default void sort(Comparator<? super E> c) {
}
!
Defender Method
Default Method
(Virtual) Extension Method
!29
Extension methods
java.util.List:
!
default void sort(Comparator<? super E> c) {
Collections.sort(this, c);
}
!
Defender Method
Default Method
(Virtual) Extension Method
!30
Java 8 extension methods
Extend interfaces with new methods
Compatibility
Default implementation
Override
Requires modification of original interface
!31
C# extension methods
“Add” methods to existing types
Without modifying original type
Defined as static methods
Called as instance methods
!32
Scala implicit classes
“Add” methods or properties to existing types
Without modifying original type
Implicit wrapper object
!33
Java 7 vs 8
Collections.sort(people, new Comparator<Person>() {
public int compare(Person x, Person y) {
return x.getName().compareTo(y.getName());
}
});
!
vs
!
people.sort(comparing(Person::getName));
!34
So far, so good?
Lambdas
Method handles
Extension methods
!35
So, what’s the catch?
© Fredrik Vraalsen 2012
What’s wrong with using List::sort ?
Modifies existing collection
Others may be using it?
Concurrency issues
Performance
!37
Streams
© Fredrik Vraalsen 2008
The old fashioned way
!39
List<RoadData> filtered = new ArrayList<>();	
int count = 0;
for (Iterator<RoadData> i = roadData.iterator();	
i.hasNext() && count < 10; ) {	
RoadData data = i.next();
if (data.getName().contains(nameQuery)) {
filtered.add(data);
count++;
}
}
Streams
!40
!
roadData.stream() 	
.filter(r -> r.getName().contains(nameQuery))	
.limit(10) 	
.collect(Collectors.toList());
Streams – pipelines
!41
!
roadData.stream() 	
.filter(r -> r.getName().contains(nameQuery))	
.limit(10) 	
.collect(Collectors.toList());	
!
!
cat roadData.txt | grep … | head > output.txt
Streams – pipelines
Source
collection, array, generator function, IO channel, ...
Intermediate operations (Stream-producing)
filter, map, ...
Terminal operations (value-producing)
!42
Performance
© Fredrik Vraalsen 2012
Streams – performance
!
people.stream()	
.filter(p -> p.getAge() >= 18)	
.map(Person::getName)	
.collect(Collectors.toList());
!44
This one goes to 11!
!
people.parallelStream()	
.filter(p -> p.getAge() >= 18)	
.map(Person::getName)	
.collect(Collectors.toList());
!45
Scala FTW!
!
people.par	
.filter(_.age >= 18)	
.map(_.name)
!46
Streams
java.util.stream
Create new results
Lazy
Parallelizable
!47
More cool stuff in Java 8
String join
Collection removeIf (≈ filter)
List sort
Map getOrDefault, putIfAbsent, replace, forEach, etc.
java.util.stream.Collectors
count, sum, average, min, max, groupingBy, etc.
java.nio.file.Files lines
!48
What’s missing?
© Fredrik Vraalsen 2012
What’s missing?
Immutability
Value types
Data structures (lists, maps, etc.)
Concurrency
!50
Some help to be found
Immutable collections
Google Guava, FunctionalJava, clj-ds
Concurrency mechanisms
Akka (Actors, STM)
!51
github.com/krukow/clj-ds
PersistentVector<Person> people = Persistents.vector(	
new Person("Fredrik", 37),	
new Person("Hedda", 2));	
!52
github.com/krukow/clj-ds
PersistentVector<Person> people = Persistents.vector(	
new Person("Fredrik", 37),	
new Person("Hedda", 2));	
!
PersistentVector<Person> morePeople =	
people.plus(new Person("Johannes", 4));
!53
github.com/krukow/clj-ds
PersistentVector<Person> people = Persistents.vector(	
new Person("Fredrik", 37),	
new Person("Hedda", 2));	
!
PersistentVector<Person> morePeople = 	
people.plus(new Person("Johannes", 4));	
!
morePeople.stream()	
.forEach(p -> System.out.println(p.getName()));
!54
Ready to
make the jump!?
© Fredrik Vraalsen 2013
Play with it!
Download – http://www.oracle.com/technetwork/java/
… or https://jdk8.java.net/download.html
Whitepapers – http://openjdk.java.net/projects/lambda/
FAQ – http://www.lambdafaq.org/
Supported in IntelliJ IDEA 12 & 13
Eclipse Java 8 beta plugin and NetBeans 8.0 RC !56
Why use X instead?
Java 8 just released
Will be a long time before you can use it in enterprise dev!
Clojure and Scala available NOW! (JDK 1.6)
Important things are still missing
!57
Want to know more?
^{Oslo "Socially Functional Programmers" #OsloSFP}
“Haskell på godt og vondt” – tonight 6pm @ Teknologihuset
http://www.meetup.com/Oslo-Socially-Functional/
Functional Programming in Java 8
http://2014.flatmap.no/
!58
Questions?
© Fredrik Vraalsen 2012
vraalsen@iterate.no / @fredriv
Java 8 - Return of the Java

Más contenido relacionado

La actualidad más candente

Java8 stream
Java8 streamJava8 stream
Java8 stream
koji lin
 
ComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical SciencesComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical Sciences
alexstorer
 

La actualidad más candente (20)

Java8 stream
Java8 streamJava8 stream
Java8 stream
 
Scalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of codeScalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of code
 
Apache Spark: Moving on from Hadoop
Apache Spark: Moving on from HadoopApache Spark: Moving on from Hadoop
Apache Spark: Moving on from Hadoop
 
Spark Schema For Free with David Szakallas
 Spark Schema For Free with David Szakallas Spark Schema For Free with David Szakallas
Spark Schema For Free with David Szakallas
 
Scalding Presentation
Scalding PresentationScalding Presentation
Scalding Presentation
 
Spark schema for free with David Szakallas
Spark schema for free with David SzakallasSpark schema for free with David Szakallas
Spark schema for free with David Szakallas
 
ComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical SciencesComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical Sciences
 
Java 8 to the rescue!?
Java 8 to the rescue!?Java 8 to the rescue!?
Java 8 to the rescue!?
 
Scala vs java 8
Scala vs java 8Scala vs java 8
Scala vs java 8
 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
JDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation streamJDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation stream
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
 
Java Language fundamental
Java Language fundamentalJava Language fundamental
Java Language fundamental
 
Gremlin's Graph Traversal Machinery
Gremlin's Graph Traversal MachineryGremlin's Graph Traversal Machinery
Gremlin's Graph Traversal Machinery
 
There's a Prolog in your Scala!
There's a Prolog in your Scala!There's a Prolog in your Scala!
There's a Prolog in your Scala!
 
An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van HovellAn Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
 
Scalding
ScaldingScalding
Scalding
 
05 Analysis of Algorithms: Heap and Quick Sort - Corrected
05 Analysis of Algorithms: Heap and Quick Sort - Corrected05 Analysis of Algorithms: Heap and Quick Sort - Corrected
05 Analysis of Algorithms: Heap and Quick Sort - Corrected
 
Scala for the doubters
Scala for the doubtersScala for the doubters
Scala for the doubters
 
Dependent dynamic rules
Dependent dynamic rulesDependent dynamic rules
Dependent dynamic rules
 
Beyond Shuffling, Tips and Tricks for Scaling Apache Spark updated for Spark ...
Beyond Shuffling, Tips and Tricks for Scaling Apache Spark updated for Spark ...Beyond Shuffling, Tips and Tricks for Scaling Apache Spark updated for Spark ...
Beyond Shuffling, Tips and Tricks for Scaling Apache Spark updated for Spark ...
 
FFW Gabrovo PMG - JavaScript 2
FFW Gabrovo PMG - JavaScript 2FFW Gabrovo PMG - JavaScript 2
FFW Gabrovo PMG - JavaScript 2
 

Similar a Java 8 - Return of the Java

FUNctional Programming in Java 8
FUNctional Programming in Java 8FUNctional Programming in Java 8
FUNctional Programming in Java 8
Richard Walker
 
Extending lifespan with Hadoop and R
Extending lifespan with Hadoop and RExtending lifespan with Hadoop and R
Extending lifespan with Hadoop and R
Radek Maciaszek
 
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
Mario Fusco
 
Apache Spark for Library Developers with William Benton and Erik Erlandson
 Apache Spark for Library Developers with William Benton and Erik Erlandson Apache Spark for Library Developers with William Benton and Erik Erlandson
Apache Spark for Library Developers with William Benton and Erik Erlandson
Databricks
 

Similar a Java 8 - Return of the Java (20)

Java 8 DOs and DON'Ts - javaBin Oslo May 2015
Java 8 DOs and DON'Ts - javaBin Oslo May 2015Java 8 DOs and DON'Ts - javaBin Oslo May 2015
Java 8 DOs and DON'Ts - javaBin Oslo May 2015
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
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 8
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Polyalgebra
PolyalgebraPolyalgebra
Polyalgebra
 
Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...
Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...
Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...
 
Writing Hadoop Jobs in Scala using Scalding
Writing Hadoop Jobs in Scala using ScaldingWriting Hadoop Jobs in Scala using Scalding
Writing Hadoop Jobs in Scala using Scalding
 
Intro to Spark and Spark SQL
Intro to Spark and Spark SQLIntro to Spark and Spark SQL
Intro to Spark and Spark SQL
 
Graph Database Query Languages
Graph Database Query LanguagesGraph Database Query Languages
Graph Database Query Languages
 
Introduction to-scala
Introduction to-scalaIntroduction to-scala
Introduction to-scala
 
EuroPython 2015 - Big Data with Python and Hadoop
EuroPython 2015 - Big Data with Python and HadoopEuroPython 2015 - Big Data with Python and Hadoop
EuroPython 2015 - Big Data with Python and Hadoop
 
Extending lifespan with Hadoop and R
Extending lifespan with Hadoop and RExtending lifespan with Hadoop and R
Extending lifespan with Hadoop and R
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
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
 
ScalaBlitz
ScalaBlitzScalaBlitz
ScalaBlitz
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Spark training-in-bangalore
Spark training-in-bangaloreSpark training-in-bangalore
Spark training-in-bangalore
 
Apache Spark for Library Developers with William Benton and Erik Erlandson
 Apache Spark for Library Developers with William Benton and Erik Erlandson Apache Spark for Library Developers with William Benton and Erik Erlandson
Apache Spark for Library Developers with William Benton and Erik Erlandson
 

Más de Fredrik Vraalsen

Más de Fredrik Vraalsen (7)

Building applications with Serverless Framework and AWS Lambda - JavaZone 2019
Building applications with Serverless Framework and AWS Lambda - JavaZone 2019Building applications with Serverless Framework and AWS Lambda - JavaZone 2019
Building applications with Serverless Framework and AWS Lambda - JavaZone 2019
 
Building applications with Serverless Framework and AWS Lambda
Building applications with Serverless Framework and AWS LambdaBuilding applications with Serverless Framework and AWS Lambda
Building applications with Serverless Framework and AWS Lambda
 
Kafka and Kafka Streams in the Global Schibsted Data Platform
Kafka and Kafka Streams in the Global Schibsted Data PlatformKafka and Kafka Streams in the Global Schibsted Data Platform
Kafka and Kafka Streams in the Global Schibsted Data Platform
 
Scala intro workshop
Scala intro workshopScala intro workshop
Scala intro workshop
 
Event stream processing using Kafka streams
Event stream processing using Kafka streamsEvent stream processing using Kafka streams
Event stream processing using Kafka streams
 
Hjelp, vi skal kode funksjonelt i Java!
Hjelp, vi skal kode funksjonelt i Java!Hjelp, vi skal kode funksjonelt i Java!
Hjelp, vi skal kode funksjonelt i Java!
 
Git i praksis - erfaringer med overgang fra ClearCase til Git
Git i praksis - erfaringer med overgang fra ClearCase til GitGit i praksis - erfaringer med overgang fra ClearCase til Git
Git i praksis - erfaringer med overgang fra ClearCase til Git
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 

Java 8 - Return of the Java