SlideShare a Scribd company logo
1 of 20

Functional Extensions in Java 8
Jörn Guy Süß
October 2016
Agenda
Motivation
Basic Principle (API Blocks)
Streams
Impedance Problems (Nulls, IO)
Questions
2
1
2
3
4
5
Why add functional to Java?
1. Syntax Improvement: Inner Classes are a syntactic pain
2. Performance for all: Fork/Join framework is for experts
3. Cloud Languages: „new“ languages have closures
3
An Example
 IntStream.iterate(0, n -> (n+1)%2)
.distinct()
.limit(10)
.forEach(System.out::println);
 Typical example: stream, closure, terminal operation
4
Create Stream Apply Mapping Export Outcomes
Invocation is lazy from the terminal operation
Attaching Functional Constructs to Java Infrastructure
• Change the parser
• Retrofit collections to work with functional
• Type inference and Functions
• Method References
5
What can you write
Lambda expression Meaning Interface
()->System.out.println() It takes no arguments and displays a single line Consumer<Void> ???
x->System.out.println(x) It takes a single argument and displays it on a
line
Consumer<T>
x->2*x It takes a single argument and returns its double Function<T>
(x,y)->x+y It takes two arguments and returns their sum BiFunction<T,U>
x -> {
int y = 2*x;
return y;
}
It takes a single argument and returns its double
using multiple statements
Function<T>
x -> y -> x + y Curried Function Function<T,
Function<U,V>>
System.out::println Method Reference Consumer<T>
6
... Typical Functional Expressions
Retrofit Collections
 Collections need to be a source of closures streams with no hassle
 We cannot break the collection implementations interface to add
methods
 Lets add them to the interface then
 Interfaces now have default methods …
 All collections now have Spliterator that produces the stream
7
Or: How interfaces got implementations
Type Check and Functions
 If a Lambda is an inner class,
how do we know if that class fits as a parameter to a method?
 We can use an interface to describe the requirement.
 Ok, but if we try to fit the lambda to the method signatures in the interface, which should
we pick if there are several fits?
 Well than we have to make that impossible.
 Interfaces with only one method?
 One functional method. The others can be default remember?
Lets call these @FunctionalInterface
 Completely clear.
8
Method References
 If I just want to invoke a method, does that mean I have to always
write a lambda and implicitly produce an inner class?
 No, we could use invokeDynamic and Method Handles from Java 7,
and you can write something like System.out::println
 In fact, we can use invokeDynamic for all lambda expressions when
we store the bytecode.
 That seems complex. Luckily stack overflow has more details:
http://stackoverflow.com/questions/30002380/why-are-java-8-
lambdas-invoked-using-invokedynamic
9
API Blocks – Sources and Sinks
 Supplier<T>s: Allow you to T get() items for streams
 Function<T,U>: You can U apply(T) them to items
 Consumers<T>s: Will accept(T) items from streams
 Predicate<T>: You can boolean test(T) items
 And lots of ...
 versions for Primitive Types, like IntSupplier and ObjDoubleConsumer
 conversion functions like ToIntFunction
10
These are the essential concepts
of stream processing
API Blocks – Special Functions and Constructs
 (Unary|Binary)Operator: Functions with homogenous argument
types
 Bi(Supplier|Function|Consumer|Predicate): Operate on
pairs:
stream = Arrays.stream(rectangles);
total = stream
.map(r -> r.scale(0.25))
.mapToInt(Rectangle::getArea)
.reduce(0,(r, s) -> r + s);
(Pair versions of the conversion functions as seen before)
11
Streams – Creating one
1. Use a .stream() method from some glue code
2. Call of(T ...) and convert the varargs array
3. Call builder(), add items, and pump it out
4. Call generate(Supplier<T>) e.g. for making endless streams
5. Call empty()
12
A stream is a sequential process abstraction
for mutable objects that is not reusable
Streams – Consuming one
Caveat:
Streams are lazy in the functional sense.
Unless and until a terminal operation is called, no processing occurs.
To terminate your stream you can:
1. Use a forEach(Ordered)() to produce a side-effect
2. Call toArray(T ...) to convert the result to an array
13
Eventually, every stream leaves the
functional zone to interface with IO
Stream: Getting a single result
 count() the elements
 min|max() biggest, smallest element
 find(First|Any)() obtain an element
 (none|all|any)Match() the logical quantifiers ∄, ∀, ∃
 sorted() find out if the stream is sorted
 reduce|collect(): aggregate elements (functional fold operation)
14
Streams are often used to „teles-
cope fold“ data into a single output
Getting a stream from a stream
 filter(): remove anything that does not match
 limit()/skip(): take only / skip N elements
 map(): apply a transformation function
 peek(): run an output on each passing item – Progress bars and loggers!
 concat(): append one stream to another
 sort() : ensure elements are ordered
 distinct(): ensure elements are distinct
15
Streams can be „conveyor belts“
for manipulating items sequentially
Do not work on
endless streams!
Numeric Streams – First Class API citizens
 Suppliers, Consumers, Predicates
 Operators on numeric values*
 Functions to convert between other types the numeric value: from, to*
 Numeric Streams with special functions for boxing
 Collectors over streams for Sums, Summaries (Hashes) and
Averages
* A version with two arguments (BiFunction) is also available
16
int, long and double have ready-made implementations of Stream Interfaces
Stream Collectors
 group sort the elements into a number of groups using a function
 partition split the elements into disjunct collections using a predicate
 joining Strings with prefix, seperator and postfix
 Conversion to Collection, List, Set, Map
17
Collectors are SQL-like domain functions to run in collect() calls
Stream, Spliterator and Parallel Processing
Each Stream is based on a Spliterator which can
 invoke a terminal operation on one (tryAdvance) or all (forEachRemaining) of its contents
 attempt to split another Spliterator of (trySplit) for parallel processing
 estimate its content size (estimateSize)
 provide its Comparator if its source is sorted
 Provide its characteristics()
based on theses Characteristics the streams framework decides if parallel processing is possible, and
enables it if desired and/or opportune.
18
parallel()/sequential() change the parallel stream processing advice
Spliterator Characteristics
IMMUTABLE the element source cannot be structurally modified; that is, elements cannot be added, replaced, or removed, so such
changes cannot occur during traversal.
CONCURRENT the element source may be safely concurrently modified (allowing additions, replacements, and/or removals) by multiple
threads without external synchronization.
NONNULL the source guarantees that encountered elements will not be null.
SIZED the value returned from estimateSize() prior to traversal or splitting represents a finite size that, in the absence of
structural source modification, represents an exact count of the number of elements that would be encountered by a
complete traversal.
SUBSIZED all Spliterators resulting from trySplit() will be both SIZED and SUBSIZED. This means that all child Spliterators,
whether direct or indirect, will be SIZED.
ORDERED an encounter order is defined for elements.
DISTINCT for each pair of encountered elements x, y, !x.equals(y).
SORTED encounter order follows a defined sort order.
Confidential – Oracle Internal/Restricted/Highly Restricted
19
Impedance Problems (Nulls, IO)
 Optional<T> is a monad that works with null Values
 empty()
 of(Nullable)(T)
 boolean isPresent() is used with filter()
and T get() is used with map()
 Streams are AutoCloseable,
create them in try-with-resources if you use IO
 Example: Stream<JarItem> JarFile.stream()
20
Facilities to handle exceptional
flow and null values

More Related Content

What's hot

java 8 new features
java 8 new features java 8 new features
java 8 new features Rohit Verma
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features OverviewSergii Stets
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8icarter09
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java langer4711
 
Java.util.concurrent.concurrent hashmap
Java.util.concurrent.concurrent hashmapJava.util.concurrent.concurrent hashmap
Java.util.concurrent.concurrent hashmapSrinivasan Raghvan
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsNewCircle Training
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Harmeet Singh(Taara)
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesRaffi Khatchadourian
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhHarmeet Singh(Taara)
 

What's hot (20)

java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java
 
Java.util.concurrent.concurrent hashmap
Java.util.concurrent.concurrent hashmapJava.util.concurrent.concurrent hashmap
Java.util.concurrent.concurrent hashmap
 
Java 8 streams
Java 8 streams Java 8 streams
Java 8 streams
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Actors model in gpars
Actors model in gparsActors model in gpars
Actors model in gpars
 
Operator overloading
Operator overloading Operator overloading
Operator overloading
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to Interfaces
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singh
 

Viewers also liked

Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8RichardWarburton
 
Introduction to functional programming with java 8
Introduction to functional programming with java 8Introduction to functional programming with java 8
Introduction to functional programming with java 8JavaBrahman
 
Functional programming principles and Java 8
Functional programming principles and Java 8Functional programming principles and Java 8
Functional programming principles and Java 8Dragos Balan
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Ganesh Samarthyam
 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday lifeAndrea Iacono
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8LivePerson
 

Viewers also liked (6)

Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
 
Introduction to functional programming with java 8
Introduction to functional programming with java 8Introduction to functional programming with java 8
Introduction to functional programming with java 8
 
Functional programming principles and Java 8
Functional programming principles and Java 8Functional programming principles and Java 8
Functional programming principles and Java 8
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday life
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 

Similar to A Brief Conceptual Introduction to Functional Java 8 and its API

Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxBruceLee275640
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerApache Traffic Server
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An OverviewIndrajit Das
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 SlidesYarikS
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2JollyRogers5
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in java 8 Dori Waldman
 
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
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalUrs Peter
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Raffi Khatchadourian
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfkarymadelaneyrenne19
 

Similar to A Brief Conceptual Introduction to Functional Java 8 and its API (20)

Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Java 8
Java 8Java 8
Java 8
 
java8
java8java8
java8
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
Java 8
Java 8Java 8
Java 8
 
JDK8 Streams
JDK8 StreamsJDK8 Streams
JDK8 Streams
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in 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...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_final
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
 
Matlab commands
Matlab commandsMatlab commands
Matlab commands
 

Recently uploaded

%+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
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
%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
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
%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
 
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
 
%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
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
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
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
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
 
%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
 
%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
 
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
 

Recently uploaded (20)

%+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...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
%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
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
%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
 
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
 
%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
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
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
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
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
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%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
 
%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
 
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
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 

A Brief Conceptual Introduction to Functional Java 8 and its API

  • 1.  Functional Extensions in Java 8 Jörn Guy Süß October 2016
  • 2. Agenda Motivation Basic Principle (API Blocks) Streams Impedance Problems (Nulls, IO) Questions 2 1 2 3 4 5
  • 3. Why add functional to Java? 1. Syntax Improvement: Inner Classes are a syntactic pain 2. Performance for all: Fork/Join framework is for experts 3. Cloud Languages: „new“ languages have closures 3
  • 4. An Example  IntStream.iterate(0, n -> (n+1)%2) .distinct() .limit(10) .forEach(System.out::println);  Typical example: stream, closure, terminal operation 4 Create Stream Apply Mapping Export Outcomes Invocation is lazy from the terminal operation
  • 5. Attaching Functional Constructs to Java Infrastructure • Change the parser • Retrofit collections to work with functional • Type inference and Functions • Method References 5
  • 6. What can you write Lambda expression Meaning Interface ()->System.out.println() It takes no arguments and displays a single line Consumer<Void> ??? x->System.out.println(x) It takes a single argument and displays it on a line Consumer<T> x->2*x It takes a single argument and returns its double Function<T> (x,y)->x+y It takes two arguments and returns their sum BiFunction<T,U> x -> { int y = 2*x; return y; } It takes a single argument and returns its double using multiple statements Function<T> x -> y -> x + y Curried Function Function<T, Function<U,V>> System.out::println Method Reference Consumer<T> 6 ... Typical Functional Expressions
  • 7. Retrofit Collections  Collections need to be a source of closures streams with no hassle  We cannot break the collection implementations interface to add methods  Lets add them to the interface then  Interfaces now have default methods …  All collections now have Spliterator that produces the stream 7 Or: How interfaces got implementations
  • 8. Type Check and Functions  If a Lambda is an inner class, how do we know if that class fits as a parameter to a method?  We can use an interface to describe the requirement.  Ok, but if we try to fit the lambda to the method signatures in the interface, which should we pick if there are several fits?  Well than we have to make that impossible.  Interfaces with only one method?  One functional method. The others can be default remember? Lets call these @FunctionalInterface  Completely clear. 8
  • 9. Method References  If I just want to invoke a method, does that mean I have to always write a lambda and implicitly produce an inner class?  No, we could use invokeDynamic and Method Handles from Java 7, and you can write something like System.out::println  In fact, we can use invokeDynamic for all lambda expressions when we store the bytecode.  That seems complex. Luckily stack overflow has more details: http://stackoverflow.com/questions/30002380/why-are-java-8- lambdas-invoked-using-invokedynamic 9
  • 10. API Blocks – Sources and Sinks  Supplier<T>s: Allow you to T get() items for streams  Function<T,U>: You can U apply(T) them to items  Consumers<T>s: Will accept(T) items from streams  Predicate<T>: You can boolean test(T) items  And lots of ...  versions for Primitive Types, like IntSupplier and ObjDoubleConsumer  conversion functions like ToIntFunction 10 These are the essential concepts of stream processing
  • 11. API Blocks – Special Functions and Constructs  (Unary|Binary)Operator: Functions with homogenous argument types  Bi(Supplier|Function|Consumer|Predicate): Operate on pairs: stream = Arrays.stream(rectangles); total = stream .map(r -> r.scale(0.25)) .mapToInt(Rectangle::getArea) .reduce(0,(r, s) -> r + s); (Pair versions of the conversion functions as seen before) 11
  • 12. Streams – Creating one 1. Use a .stream() method from some glue code 2. Call of(T ...) and convert the varargs array 3. Call builder(), add items, and pump it out 4. Call generate(Supplier<T>) e.g. for making endless streams 5. Call empty() 12 A stream is a sequential process abstraction for mutable objects that is not reusable
  • 13. Streams – Consuming one Caveat: Streams are lazy in the functional sense. Unless and until a terminal operation is called, no processing occurs. To terminate your stream you can: 1. Use a forEach(Ordered)() to produce a side-effect 2. Call toArray(T ...) to convert the result to an array 13 Eventually, every stream leaves the functional zone to interface with IO
  • 14. Stream: Getting a single result  count() the elements  min|max() biggest, smallest element  find(First|Any)() obtain an element  (none|all|any)Match() the logical quantifiers ∄, ∀, ∃  sorted() find out if the stream is sorted  reduce|collect(): aggregate elements (functional fold operation) 14 Streams are often used to „teles- cope fold“ data into a single output
  • 15. Getting a stream from a stream  filter(): remove anything that does not match  limit()/skip(): take only / skip N elements  map(): apply a transformation function  peek(): run an output on each passing item – Progress bars and loggers!  concat(): append one stream to another  sort() : ensure elements are ordered  distinct(): ensure elements are distinct 15 Streams can be „conveyor belts“ for manipulating items sequentially Do not work on endless streams!
  • 16. Numeric Streams – First Class API citizens  Suppliers, Consumers, Predicates  Operators on numeric values*  Functions to convert between other types the numeric value: from, to*  Numeric Streams with special functions for boxing  Collectors over streams for Sums, Summaries (Hashes) and Averages * A version with two arguments (BiFunction) is also available 16 int, long and double have ready-made implementations of Stream Interfaces
  • 17. Stream Collectors  group sort the elements into a number of groups using a function  partition split the elements into disjunct collections using a predicate  joining Strings with prefix, seperator and postfix  Conversion to Collection, List, Set, Map 17 Collectors are SQL-like domain functions to run in collect() calls
  • 18. Stream, Spliterator and Parallel Processing Each Stream is based on a Spliterator which can  invoke a terminal operation on one (tryAdvance) or all (forEachRemaining) of its contents  attempt to split another Spliterator of (trySplit) for parallel processing  estimate its content size (estimateSize)  provide its Comparator if its source is sorted  Provide its characteristics() based on theses Characteristics the streams framework decides if parallel processing is possible, and enables it if desired and/or opportune. 18 parallel()/sequential() change the parallel stream processing advice
  • 19. Spliterator Characteristics IMMUTABLE the element source cannot be structurally modified; that is, elements cannot be added, replaced, or removed, so such changes cannot occur during traversal. CONCURRENT the element source may be safely concurrently modified (allowing additions, replacements, and/or removals) by multiple threads without external synchronization. NONNULL the source guarantees that encountered elements will not be null. SIZED the value returned from estimateSize() prior to traversal or splitting represents a finite size that, in the absence of structural source modification, represents an exact count of the number of elements that would be encountered by a complete traversal. SUBSIZED all Spliterators resulting from trySplit() will be both SIZED and SUBSIZED. This means that all child Spliterators, whether direct or indirect, will be SIZED. ORDERED an encounter order is defined for elements. DISTINCT for each pair of encountered elements x, y, !x.equals(y). SORTED encounter order follows a defined sort order. Confidential – Oracle Internal/Restricted/Highly Restricted 19
  • 20. Impedance Problems (Nulls, IO)  Optional<T> is a monad that works with null Values  empty()  of(Nullable)(T)  boolean isPresent() is used with filter() and T get() is used with map()  Streams are AutoCloseable, create them in try-with-resources if you use IO  Example: Stream<JarItem> JarFile.stream() 20 Facilities to handle exceptional flow and null values