SlideShare a Scribd company logo
1 of 27
Java User Group - 9/2/2015
Introduction to Java 8 Streams
Louvain-La-Neuve
Belgium
Marc Tritchler
Some Theory
• Why Java 8
• Java 8 Streams, Lambdas
Java Platform is simple … but
JEEJMS, JSF, JSP, EJB, CDI, JAX-WS, JAX-RS,
JPA, JTA, JNDI, ….
JDK
JRE
JVM
JSE
JSR
JCP
History of Java SE (simplified)
http://en.wikipedia.org/wiki/Java_version_history
• SE vs EE
• J2 SE 1.4  2002 (dark ages but still a lot in the wild)
• J2 SE 5.0  2004 (ancient but major enhancements)
• Java SE 6  2006 (not major enhancements)
• Java SE 7  2011 (yes, its becoming sexy)
• Java SE 8  2014 (huge changes … Oh My God)
† ( No supported anymore by Oracle)
J2 SE 1.4 (2002)
• assert
• regular expressions
• exception chaining
• Internet Protocol version 6 (IPv6) support
• non-blocking IO (named New Input/Output, NIO)
• logging API
• image I/O API for reading and writing images in formats like JPEG
and PNG
• integrated XML parser and XSLT processor (JAXP)
• integrated security and cryptography extensions (JCE, JSSE, JAAS)
• Java Web Start
• Preferences API (java.util.prefs)
J2 SE 1.5 (2004)
• Generics
• annotations; allows language constructs such as classes and methods to be tagged with additional
data, which can then be processed by metadata-aware utilities. (Specified by JSR 175.)
• Autoboxing/unboxing: Automatic conversions between primitive types (such as int) and primitive
wrapper classes (such as Integer). (Specified by JSR 201.)
• Enumerations: The enum keyword creates a typesafe, ordered list of values (such as Day.MONDAY,
Day.TUESDAY, etc.). Previously this could only be achieved by non-typesafe constant integers or
manually constructed classes (typesafe enum pattern). (Specified by JSR 201.)
• Varargs: The last parameter of a method can now be declared using a type name followed by three
dots (e.g. void drawtext(String... lines)). In the calling code any number of parameters of that type
can be used and they are then placed in an array to be passed to the method, or alternatively the
calling code can pass an array of that type.
• Enhanced for each loop: The for loop syntax is extended with special syntax for iterating over each
member of either an array or any Iterable, such as the standard Collection classes. (Specified by JSR
201.)
• Fix the previously broken semantics of the Java Memory Model, which defines how threads
interact through memory.
• Static imports
Java SE 6 (2006)
• Support for older Win9x versions dropped
• Scripting Language Support Generic API for tight integration with scripting
languages, and built-in Mozilla JavaScript Rhino integration
• Dramatic performance improvements for the core platform and Swing.
• Improved Web Service support through JAX-WS
• JDBC 4.0 support.
• Java Compiler API : an API allowing a Java program to select and invoke a
Java Compiler programmatically.
• Upgrade of JAXB to version 2.0: Including integration of a StAX parser.
Support for pluggable annotations
• Many GUI improvements, such as integration of SwingWorker in the API,
table sorting and filtering, and true Swing double-buffering (eliminating
the gray-area effect). JVM improvements include: synchronization and
compiler performance optimizations, new algorithms and upgrades to
existing garbage collection algorithms, and application start-up
performance.[27
Java SE 7
• JVM support for dynamic languages Scala, …
• Compressed 64-bit pointers(available in Java 6 with -XX:+UseCompressedOops)
• Strings in switch
• Automatic resource management in try-statement
• Improved type inference for generic instance creation, aka the diamond operator <>
• Simplified varargs method declaration
• Binary integer literals
• Allowing underscores in numeric literals
• Catching multiple exception types and rethrowing exceptions with improved type checking
• Concurrency utilities under JSR 166
• NIO.2 New file I/O library to enhance platform independence and add support for metadata and
symbolic links.
• Timsort is used to sort collections and arrays of objects instead of merge sort
• Library-level support for elliptic curve cryptography algorithms
• An XRender pipeline for Java 2D, which improves handling of features specific to modern GPUs
• New platform APIs for the graphics features originally implemented in version 6u10 as
unsupported APIs
• Enhanced library-level support for new network protocols, including SCTP and Sockets Direct
Protocol
• Upstream updates to XML and Unicode
Java 8 (2014)
• lambda expressions (unofficially closures)
• default methods (virtual extension methods) which make multiple inheritance possible in Java.
There was an ongoing debate in the Java community on whether to add support for lambda
expressions.[
Sun later declared that lambda expressions would be included in Java and asked for
community input to refine the feature. Supporting lambda expressions also allows to perform
functional-style operations on streams of elements, such as MapReduce-inspired transformations
on collections. Default methods allow an author of API to add new methods to an interface without
breaking the old code using it. It also provides a way to use multiple inheritance, multiple
inheritance of implementation more precisely.
• JSR 223, JEP 174: Project Nashorn, a JavaScript runtime which allows developers to embed
JavaScript code within applications
• Annotation on Java Types
• Unsigned Integer Arithmetic
• JSR 337, JEP 120: Repeating annotations
• JSR 310, JEP 150: Date and Time API
• JEP 178: Statically-linked JNI libraries
• JEP 153: Launch JavaFX applications (direct launching of JavaFX application JARs)
• JEP 122: Remove the permanent generation
• Default methods (for API dev)
• Functional interfaces (new ones)
What is a Stream ?
sequence of elements from a source that
supports data processing operations
Ex: stream of bytes 4,5,9,0, ….
Why Streams ?
WHAT vs HOW
• Like SQL … concentrate on the what, not the
how = working at higher level …
Ex: SELECT name from USERS;
vs. C program (main, fopen(), while())
• Internal loop vs external
Java 8 – Streams
(java.util.stream)
• Old way (Java 7): Collections
• Modern way (Java 8): Collections + Streams
– Collections store & access data
– Streams process data (filter, group, …) in 1 or
multicore 
Stream pre-requesites
• Functional programming  pass functions as
parameters
• Lambda = anonymous function
• Method references ::
• Functional Interfaces
Predicate  test()
Supplier<T>  get()
Consumer<T>  accept()
…
Stream creations
• From collections: List & Set new methods:
stream()
parallelStream()
• From file, from Arrays, …
• For primitive data types int, long, double
– IntStream, LongStream, DoubleStream
– sum() and average()
– mapToInt()and mapToObj()
Stream operations
• Intermediate or terminal
– Intermediate: return Streams  like LEGO or
UNIX commands: they can be combined !
ex: filter, map, sorted
– Terminal: don't return a Stream (void or type)
ex: forEach
Example
Stream.iterate(0, n -> n + 3).limit(10).forEach(System.out::println);
• Complete javadoc
http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
Stream termination
• forEach
• reduce
• collect
• flatMap
Part 2 - Practice
Requirements
– Java 8 JDK, not the JRE LOL
– IDE (Eclipse, NetBeans, …)
Sources
– http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
– Java 8 In Action (Manning Editions)
Streams : simple examples
// from Collections
Arrays.asList("a1", "a2", "a3").stream().findFirst().ifPresent(System.out::println);
// from Objects references
Stream.of("a1", "a2", "a3").findFirst().ifPresent(System.out::println);
// empty Stream
Stream.empty();
// IntStream
IntStream.range(1, 4).forEach(System.out::println);
// Arrays -> Stream
Arrays.stream(new int[] {1, 2, 3}).map(n -> 2 * n + 1) .average()
.ifPresent(System.out::println);
// Stream -> InStream
Stream.of("a1", "a2", "a3") .map(s -> s.substring(1)).mapToInt(Integer::parseInt) .max()
.ifPresent(System.out::println);
// IntStream -> Stream
IntStream.range(1, 4).mapToObj(i -> "a" + i).forEach(System.out::println);
// Stream -> InStream -> Stream (LOL)
Stream.of(1.0, 2.0, 3.0).mapToInt(Double::intValue).mapToObj(i -> "a" + i)
.forEach(System.out::println);
Processing Order
• Intermediate operations laziness (=
intermediate operations will only be executed
when a terminal operation is present)
Ex 1: Stream.of("d2", "a2", "b1", "b3", "c")
.filter(s -> { System.out.println("filter: " + s); return true; });
 NO OUTPUT
.forEach(s -> System.out.println("forEach: " + s));
 SURPRIZE: filter, foreach, filter, foreach, … processing order
Ex 2: Stream.of("d2", "a2", "b1", "b3", "c")
.map(s -> { System.out.println("map: " + s); return s.toUpperCase(); })
.anyMatch(s -> { System.out.println("anyMatch: " + s); return s.startsWith("A"); });
 not all elements processed
Order Matters … on large data sets
Example: 2 intermediate operations (map() and filter() and 1 terminal operation
forEach())
// map & filter called 5 times, forEach 1
Stream.of("d2", "a2", "b1", "b3", "c")
.map(s -> { System.out.println("map: " + s); return s.toUpperCase(); })
.filter(s -> { System.out.println("filter: " + s); return s.startsWith("A"); })
.forEach(s -> System.out.println("forEach: " + s));
Invert map() and filter():
// map called only 1 time
Stream.of("d2", "a2", "b1", "b3", "c")
.filter(s -> { System.out.println("filter: " + s); return s.startsWith("a"); })
.map(s -> { System.out.println("map: " + s); return s.toUpperCase(); })
.forEach(s -> System.out.println("forEach: " + s));
Statefull intermediate operations
// sorted: 8, filter: 5, map: 1, forEach: 1
Stream.of("d2", "a2", "b1", "b3", "c")
.sorted((s1, s2) -> { System.out.printf("sort: %s; %sn", s1, s2); return s1.compareTo(s2); }) // statefull
.filter(s -> { System.out.println("filter: " + s); return s.startsWith("a"); })
.map(s -> { System.out.println("map: " + s); return s.toUpperCase(); })
.forEach(s -> System.out.println("forEach: " + s));
filter()  sorted()
// sorted: 0, filter: 5, map:1, forEach: 1
Stream.of("d2", "a2", "b1", "b3", "c")
.filter(s -> { System.out.println("filter: " + s); return s.startsWith("a"); })
.sorted((s1, s2) -> { System.out.printf("sort: %s; %sn", s1, s2); return s1.compareTo(s2); })
.map(s -> { System.out.println("map: " + s); return s.toUpperCase(); })
.forEach(s -> System.out.println("forEach: " + s));
Reusing Streams
• Java 8 streams cannot be reused (as soon as
you call any terminal operation the stream is
closed)
Stream<String> stream = Stream.of("d2", "a2", "b1", "b3", "c")
.filter(s -> s.startsWith("a"));
stream.anyMatch(s -> true); // ok
stream.noneMatch(s -> true); // exception
• To overcome this limitation we have to to create a new stream chain for
every terminal operation we want to execute, e.g. we could create a
stream supplier to construct a new stream with all intermediate
operations already set up:
Advanced Operations
• collect()
• flatMap()
• reduce()
collect()
• Terminal operation expecting a Collector
(Stream  Colletion or other)
• Collector http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collector.html
– Supplier, Accumulator, Combinern, Finisher
• Collectors http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html
static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,?
extends K> keyMapper, Function<? super T,? extends U>
valueMapper)
Returns a Collector that accumulates elements into a Map whose keys and
values are the result of applying the provided mapping functions to the
input elements.
flatMap
reduce
A more complete example
• Create Transaction class
• Create Enum for currencies

More Related Content

What's hot

An Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional ParadigmsAn Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional Paradigms
Miles Sabin
 
Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...
Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...
Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...
Lucidworks
 
Solr Black Belt Pre-conference
Solr Black Belt Pre-conferenceSolr Black Belt Pre-conference
Solr Black Belt Pre-conference
Erik Hatcher
 
Lucene for Solr Developers
Lucene for Solr DevelopersLucene for Solr Developers
Lucene for Solr Developers
Erik Hatcher
 

What's hot (20)

Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
 
An Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional ParadigmsAn Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional Paradigms
 
Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...
Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...
Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...
 
2 P Seminar
2 P Seminar2 P Seminar
2 P Seminar
 
Introduction to Solr
Introduction to SolrIntroduction to Solr
Introduction to Solr
 
Solr Black Belt Pre-conference
Solr Black Belt Pre-conferenceSolr Black Belt Pre-conference
Solr Black Belt Pre-conference
 
Lucene for Solr Developers
Lucene for Solr DevelopersLucene for Solr Developers
Lucene for Solr Developers
 
Solr 4
Solr 4Solr 4
Solr 4
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Advanced Production Debugging
Advanced Production DebuggingAdvanced Production Debugging
Advanced Production Debugging
 
Lucene's Latest (for Libraries)
Lucene's Latest (for Libraries)Lucene's Latest (for Libraries)
Lucene's Latest (for Libraries)
 
Debugging Your Production JVM
Debugging Your Production JVMDebugging Your Production JVM
Debugging Your Production JVM
 
Collections forceawakens
Collections forceawakensCollections forceawakens
Collections forceawakens
 
The Road to Lambda - Mike Duigou
The Road to Lambda - Mike DuigouThe Road to Lambda - Mike Duigou
The Road to Lambda - Mike Duigou
 
firststeps
firststepsfirststeps
firststeps
 
Java Language fundamental
Java Language fundamentalJava Language fundamental
Java Language fundamental
 
Functional java 8
Functional java 8Functional java 8
Functional java 8
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
04 darwino concepts and utility classes
04   darwino concepts and utility classes04   darwino concepts and utility classes
04 darwino concepts and utility classes
 
Clojure, Plain and Simple
Clojure, Plain and SimpleClojure, Plain and Simple
Clojure, Plain and Simple
 

Viewers also liked

Viewers also liked (12)

Java user group Louvain-La-Neuve
Java user group Louvain-La-NeuveJava user group Louvain-La-Neuve
Java user group Louvain-La-Neuve
 
Final Multigenre Project by Shanequa Perry
Final Multigenre Project by Shanequa PerryFinal Multigenre Project by Shanequa Perry
Final Multigenre Project by Shanequa Perry
 
Help eps
Help epsHelp eps
Help eps
 
Celula procariota
Celula procariotaCelula procariota
Celula procariota
 
JUG louvain websockets
JUG louvain websocketsJUG louvain websockets
JUG louvain websockets
 
Multigenre project by Shanequa Perry
Multigenre project by Shanequa Perry Multigenre project by Shanequa Perry
Multigenre project by Shanequa Perry
 
Top 10 dodelijkste landslangen
Top 10 dodelijkste landslangenTop 10 dodelijkste landslangen
Top 10 dodelijkste landslangen
 
Module 11
Module 11Module 11
Module 11
 
Multigenre project
Multigenre projectMultigenre project
Multigenre project
 
TPACK
TPACKTPACK
TPACK
 
Study on Implementation of LED Lights for Industrial Lighting to optimize pow...
Study on Implementation of LED Lights for Industrial Lighting to optimize pow...Study on Implementation of LED Lights for Industrial Lighting to optimize pow...
Study on Implementation of LED Lights for Industrial Lighting to optimize pow...
 
Juglouvain http revisited
Juglouvain http revisitedJuglouvain http revisited
Juglouvain http revisited
 

Similar to Java user group 2015 02-09-java8

Typesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayTypesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and Play
Luka Zakrajšek
 

Similar to Java user group 2015 02-09-java8 (20)

Java Programming - 01 intro to java
Java Programming - 01 intro to javaJava Programming - 01 intro to java
Java Programming - 01 intro to java
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
A brief tour of modern Java
A brief tour of modern JavaA brief tour of modern Java
A brief tour of modern Java
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
JavaOne_2010
JavaOne_2010JavaOne_2010
JavaOne_2010
 
De Java 8 a Java 11 y 14
De Java 8 a Java 11 y 14De Java 8 a Java 11 y 14
De Java 8 a Java 11 y 14
 
Java 8
Java 8Java 8
Java 8
 
Using existing language skillsets to create large-scale, cloud-based analytics
Using existing language skillsets to create large-scale, cloud-based analyticsUsing existing language skillsets to create large-scale, cloud-based analytics
Using existing language skillsets to create large-scale, cloud-based analytics
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New Features
 
De Java 8 ate Java 14
De Java 8 ate Java 14De Java 8 ate Java 14
De Java 8 ate Java 14
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
 
What’s expected in Java 9
What’s expected in Java 9What’s expected in Java 9
What’s expected in Java 9
 
Typesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayTypesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and Play
 
A tour of Java and the JVM
A tour of Java and the JVMA tour of Java and the JVM
A tour of Java and the JVM
 
AMIS Oracle OpenWorld 2013 Review Part 3 - Fusion Middleware
AMIS Oracle OpenWorld 2013 Review Part 3 - Fusion MiddlewareAMIS Oracle OpenWorld 2013 Review Part 3 - Fusion Middleware
AMIS Oracle OpenWorld 2013 Review Part 3 - Fusion Middleware
 
JEE Programming - 01 Introduction
JEE Programming - 01 IntroductionJEE Programming - 01 Introduction
JEE Programming - 01 Introduction
 
Apache Big Data EU 2016: Building Streaming Applications with Apache Apex
Apache Big Data EU 2016: Building Streaming Applications with Apache ApexApache Big Data EU 2016: Building Streaming Applications with Apache Apex
Apache Big Data EU 2016: Building Streaming Applications with Apache Apex
 
JCConf 2018 - Retrospect and Prospect of Java
JCConf 2018 - Retrospect and Prospect of JavaJCConf 2018 - Retrospect and Prospect of Java
JCConf 2018 - Retrospect and Prospect of Java
 
Static analysis of java enterprise applications
Static analysis of java enterprise applicationsStatic analysis of java enterprise applications
Static analysis of java enterprise applications
 
JavaOne 2011 Recap
JavaOne 2011 RecapJavaOne 2011 Recap
JavaOne 2011 Recap
 

Recently uploaded

Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
soniya singh
 
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
@Chandigarh #call #Girls 9053900678 @Call #Girls in @Punjab 9053900678
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
sexy call girls service in goa
 
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Call Girls In Delhi Whatsup 9873940964 Enjoy Unlimited Pleasure
 

Recently uploaded (20)

Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
 
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
 
Call Now ☎ 8264348440 !! Call Girls in Rani Bagh Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Rani Bagh Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Rani Bagh Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Rani Bagh Escort Service Delhi N.C.R.
 
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls DubaiDubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
 
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
 
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
 
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
 
On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024
 
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
 
VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
 
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
 
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
 
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
 
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night StandHot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
 
Russian Call Girls in %(+971524965298 )# Call Girls in Dubai
Russian Call Girls in %(+971524965298  )#  Call Girls in DubaiRussian Call Girls in %(+971524965298  )#  Call Girls in Dubai
Russian Call Girls in %(+971524965298 )# Call Girls in Dubai
 
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
 
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
 
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
 

Java user group 2015 02-09-java8

  • 1. Java User Group - 9/2/2015 Introduction to Java 8 Streams Louvain-La-Neuve Belgium Marc Tritchler
  • 2. Some Theory • Why Java 8 • Java 8 Streams, Lambdas
  • 3. Java Platform is simple … but JEEJMS, JSF, JSP, EJB, CDI, JAX-WS, JAX-RS, JPA, JTA, JNDI, …. JDK JRE JVM JSE JSR JCP
  • 4. History of Java SE (simplified) http://en.wikipedia.org/wiki/Java_version_history • SE vs EE • J2 SE 1.4  2002 (dark ages but still a lot in the wild) • J2 SE 5.0  2004 (ancient but major enhancements) • Java SE 6  2006 (not major enhancements) • Java SE 7  2011 (yes, its becoming sexy) • Java SE 8  2014 (huge changes … Oh My God) † ( No supported anymore by Oracle)
  • 5. J2 SE 1.4 (2002) • assert • regular expressions • exception chaining • Internet Protocol version 6 (IPv6) support • non-blocking IO (named New Input/Output, NIO) • logging API • image I/O API for reading and writing images in formats like JPEG and PNG • integrated XML parser and XSLT processor (JAXP) • integrated security and cryptography extensions (JCE, JSSE, JAAS) • Java Web Start • Preferences API (java.util.prefs)
  • 6. J2 SE 1.5 (2004) • Generics • annotations; allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities. (Specified by JSR 175.) • Autoboxing/unboxing: Automatic conversions between primitive types (such as int) and primitive wrapper classes (such as Integer). (Specified by JSR 201.) • Enumerations: The enum keyword creates a typesafe, ordered list of values (such as Day.MONDAY, Day.TUESDAY, etc.). Previously this could only be achieved by non-typesafe constant integers or manually constructed classes (typesafe enum pattern). (Specified by JSR 201.) • Varargs: The last parameter of a method can now be declared using a type name followed by three dots (e.g. void drawtext(String... lines)). In the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method, or alternatively the calling code can pass an array of that type. • Enhanced for each loop: The for loop syntax is extended with special syntax for iterating over each member of either an array or any Iterable, such as the standard Collection classes. (Specified by JSR 201.) • Fix the previously broken semantics of the Java Memory Model, which defines how threads interact through memory. • Static imports
  • 7. Java SE 6 (2006) • Support for older Win9x versions dropped • Scripting Language Support Generic API for tight integration with scripting languages, and built-in Mozilla JavaScript Rhino integration • Dramatic performance improvements for the core platform and Swing. • Improved Web Service support through JAX-WS • JDBC 4.0 support. • Java Compiler API : an API allowing a Java program to select and invoke a Java Compiler programmatically. • Upgrade of JAXB to version 2.0: Including integration of a StAX parser. Support for pluggable annotations • Many GUI improvements, such as integration of SwingWorker in the API, table sorting and filtering, and true Swing double-buffering (eliminating the gray-area effect). JVM improvements include: synchronization and compiler performance optimizations, new algorithms and upgrades to existing garbage collection algorithms, and application start-up performance.[27
  • 8. Java SE 7 • JVM support for dynamic languages Scala, … • Compressed 64-bit pointers(available in Java 6 with -XX:+UseCompressedOops) • Strings in switch • Automatic resource management in try-statement • Improved type inference for generic instance creation, aka the diamond operator <> • Simplified varargs method declaration • Binary integer literals • Allowing underscores in numeric literals • Catching multiple exception types and rethrowing exceptions with improved type checking • Concurrency utilities under JSR 166 • NIO.2 New file I/O library to enhance platform independence and add support for metadata and symbolic links. • Timsort is used to sort collections and arrays of objects instead of merge sort • Library-level support for elliptic curve cryptography algorithms • An XRender pipeline for Java 2D, which improves handling of features specific to modern GPUs • New platform APIs for the graphics features originally implemented in version 6u10 as unsupported APIs • Enhanced library-level support for new network protocols, including SCTP and Sockets Direct Protocol • Upstream updates to XML and Unicode
  • 9. Java 8 (2014) • lambda expressions (unofficially closures) • default methods (virtual extension methods) which make multiple inheritance possible in Java. There was an ongoing debate in the Java community on whether to add support for lambda expressions.[ Sun later declared that lambda expressions would be included in Java and asked for community input to refine the feature. Supporting lambda expressions also allows to perform functional-style operations on streams of elements, such as MapReduce-inspired transformations on collections. Default methods allow an author of API to add new methods to an interface without breaking the old code using it. It also provides a way to use multiple inheritance, multiple inheritance of implementation more precisely. • JSR 223, JEP 174: Project Nashorn, a JavaScript runtime which allows developers to embed JavaScript code within applications • Annotation on Java Types • Unsigned Integer Arithmetic • JSR 337, JEP 120: Repeating annotations • JSR 310, JEP 150: Date and Time API • JEP 178: Statically-linked JNI libraries • JEP 153: Launch JavaFX applications (direct launching of JavaFX application JARs) • JEP 122: Remove the permanent generation • Default methods (for API dev) • Functional interfaces (new ones)
  • 10. What is a Stream ? sequence of elements from a source that supports data processing operations Ex: stream of bytes 4,5,9,0, ….
  • 11. Why Streams ? WHAT vs HOW • Like SQL … concentrate on the what, not the how = working at higher level … Ex: SELECT name from USERS; vs. C program (main, fopen(), while()) • Internal loop vs external
  • 12. Java 8 – Streams (java.util.stream) • Old way (Java 7): Collections • Modern way (Java 8): Collections + Streams – Collections store & access data – Streams process data (filter, group, …) in 1 or multicore 
  • 13. Stream pre-requesites • Functional programming  pass functions as parameters • Lambda = anonymous function • Method references :: • Functional Interfaces Predicate  test() Supplier<T>  get() Consumer<T>  accept() …
  • 14. Stream creations • From collections: List & Set new methods: stream() parallelStream() • From file, from Arrays, … • For primitive data types int, long, double – IntStream, LongStream, DoubleStream – sum() and average() – mapToInt()and mapToObj()
  • 15. Stream operations • Intermediate or terminal – Intermediate: return Streams  like LEGO or UNIX commands: they can be combined ! ex: filter, map, sorted – Terminal: don't return a Stream (void or type) ex: forEach Example Stream.iterate(0, n -> n + 3).limit(10).forEach(System.out::println); • Complete javadoc http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
  • 16. Stream termination • forEach • reduce • collect • flatMap
  • 17. Part 2 - Practice Requirements – Java 8 JDK, not the JRE LOL – IDE (Eclipse, NetBeans, …) Sources – http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/ – Java 8 In Action (Manning Editions)
  • 18. Streams : simple examples // from Collections Arrays.asList("a1", "a2", "a3").stream().findFirst().ifPresent(System.out::println); // from Objects references Stream.of("a1", "a2", "a3").findFirst().ifPresent(System.out::println); // empty Stream Stream.empty(); // IntStream IntStream.range(1, 4).forEach(System.out::println); // Arrays -> Stream Arrays.stream(new int[] {1, 2, 3}).map(n -> 2 * n + 1) .average() .ifPresent(System.out::println); // Stream -> InStream Stream.of("a1", "a2", "a3") .map(s -> s.substring(1)).mapToInt(Integer::parseInt) .max() .ifPresent(System.out::println); // IntStream -> Stream IntStream.range(1, 4).mapToObj(i -> "a" + i).forEach(System.out::println); // Stream -> InStream -> Stream (LOL) Stream.of(1.0, 2.0, 3.0).mapToInt(Double::intValue).mapToObj(i -> "a" + i) .forEach(System.out::println);
  • 19. Processing Order • Intermediate operations laziness (= intermediate operations will only be executed when a terminal operation is present) Ex 1: Stream.of("d2", "a2", "b1", "b3", "c") .filter(s -> { System.out.println("filter: " + s); return true; });  NO OUTPUT .forEach(s -> System.out.println("forEach: " + s));  SURPRIZE: filter, foreach, filter, foreach, … processing order Ex 2: Stream.of("d2", "a2", "b1", "b3", "c") .map(s -> { System.out.println("map: " + s); return s.toUpperCase(); }) .anyMatch(s -> { System.out.println("anyMatch: " + s); return s.startsWith("A"); });  not all elements processed
  • 20. Order Matters … on large data sets Example: 2 intermediate operations (map() and filter() and 1 terminal operation forEach()) // map & filter called 5 times, forEach 1 Stream.of("d2", "a2", "b1", "b3", "c") .map(s -> { System.out.println("map: " + s); return s.toUpperCase(); }) .filter(s -> { System.out.println("filter: " + s); return s.startsWith("A"); }) .forEach(s -> System.out.println("forEach: " + s)); Invert map() and filter(): // map called only 1 time Stream.of("d2", "a2", "b1", "b3", "c") .filter(s -> { System.out.println("filter: " + s); return s.startsWith("a"); }) .map(s -> { System.out.println("map: " + s); return s.toUpperCase(); }) .forEach(s -> System.out.println("forEach: " + s));
  • 21. Statefull intermediate operations // sorted: 8, filter: 5, map: 1, forEach: 1 Stream.of("d2", "a2", "b1", "b3", "c") .sorted((s1, s2) -> { System.out.printf("sort: %s; %sn", s1, s2); return s1.compareTo(s2); }) // statefull .filter(s -> { System.out.println("filter: " + s); return s.startsWith("a"); }) .map(s -> { System.out.println("map: " + s); return s.toUpperCase(); }) .forEach(s -> System.out.println("forEach: " + s)); filter()  sorted() // sorted: 0, filter: 5, map:1, forEach: 1 Stream.of("d2", "a2", "b1", "b3", "c") .filter(s -> { System.out.println("filter: " + s); return s.startsWith("a"); }) .sorted((s1, s2) -> { System.out.printf("sort: %s; %sn", s1, s2); return s1.compareTo(s2); }) .map(s -> { System.out.println("map: " + s); return s.toUpperCase(); }) .forEach(s -> System.out.println("forEach: " + s));
  • 22. Reusing Streams • Java 8 streams cannot be reused (as soon as you call any terminal operation the stream is closed) Stream<String> stream = Stream.of("d2", "a2", "b1", "b3", "c") .filter(s -> s.startsWith("a")); stream.anyMatch(s -> true); // ok stream.noneMatch(s -> true); // exception • To overcome this limitation we have to to create a new stream chain for every terminal operation we want to execute, e.g. we could create a stream supplier to construct a new stream with all intermediate operations already set up:
  • 23. Advanced Operations • collect() • flatMap() • reduce()
  • 24. collect() • Terminal operation expecting a Collector (Stream  Colletion or other) • Collector http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collector.html – Supplier, Accumulator, Combinern, Finisher • Collectors http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper) Returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.
  • 27. A more complete example • Create Transaction class • Create Enum for currencies

Editor's Notes

  1. EAR, JAR, WAR, RAR JDK, JRE, JVM, JEE, JMS, JSF, JSP, CDI,