Java 8 Lambdas and the Streaming API
Michael RemijanSystem Architect,
Federal Reserve Bank St. Louis
Level: Intermediate
75
Where I work?• Federal Reserve Bank St. Louis• Since 2014
http://github.com/mjremijan http://slideshare.net/mjremijan
What I do?• Java Enterprise (Java EE)
– System Architect– Developer
• Since 1999• Industries
– B2C and B2B commerce, manufacturing, astronomy, agriculture, telecommunications, national defense, healthcare, and financial areas
http://github.com/mjremijan http://slideshare.net/mjremijan
What I do? (cont.)• Author
– EJB 3 In Action Second Edition• 2014
• Blogger– http://mjremijan.blogspot.com
http://github.com/mjremijan http://slideshare.net/mjremijan
What I do? (cont.)• Adjunct Instructor
– Since 2009• Java I & II
http://github.com/mjremijan http://slideshare.net/mjremijan
Where to find [email protected]@mjremijanhttp://mjremijan.blogspot.comhttps://github.com/mjremijanhttp://www.slideshare.net/mjremijan
http://github.com/mjremijan http://slideshare.net/mjremijan
Where’s this material?https://github.com/mjremijan/live360-streamshttp://www.slideshare.net/mjremijan
http://github.com/mjremijan http://slideshare.net/mjremijan
What we’re going to talk about• Functional programming in Java 8• Lambdas
– What is a Lambda?– How do they relate to objects?
• Stream API– What is a Stream?– How are they used to process collections/lists
http://github.com/mjremijan http://slideshare.net/mjremijan
What’s the environment?NetBeans 8.1
Java 8– jdk1.8.0_65_x64
http://github.com/mjremijan http://slideshare.net/mjremijan
http://blog.takipi.com/5-features-in-java-8-that-will-change-how-
you-code/
LambdasBrief Introduction
http://github.com/mjremijan http://slideshare.net/mjremijan
http://viralpatel.net/blogs/lambda-expressions-java-tutorial/
Before Java 8: Objects• Objects are needed for
everything• Cannot use functions w/o
an Object
http://github.com/mjremijan http://slideshare.net/mjremijan
After Java 8: Lambdas• Enter Lambdas• Allow functions/methods
to be used outside an Object
• Pass lambdas (methods) around
– Not objects!
http://github.com/mjremijan http://slideshare.net/mjremijan
StreamsBrief Introduction
http://github.com/mjremijan http://slideshare.net/mjremijan
http://www.deadcoderising.com/java-8-no-more-loops/
Before Java 8: Iterator• Collections heavily follow
the Gang of Four iterator pattern
• java.util.Iterator• java.lang.Iterable<T>• External access to a
collection’s contents
http://github.com/mjremijan http://slideshare.net/mjremijan
After Java 8: Streams• Enter Streams• Access to collection
contents now internalized• Pass Lambda to apply for
each element.
http://github.com/mjremijan http://slideshare.net/mjremijan
General stream usageCollection .stream() .intermediateOperation() .intermediateOperation() .intermediateOperation() ... .terminalOperation()
.stream() .intermediateOperation() .intermediateOperation() .intermediateOperation() ... .terminalOperation()
;
String str = ints .stream() .map(i -> String.valueOf(i)) .reduce((s1, s2) -> s1 + ", " + s2) .get();
http://github.com/mjremijan http://slideshare.net/mjremijan
Intermediate operations• Operation performed on each stream
element• Results in a new stream• Lazy
– A terminal operation is needed
• Examples– Filter– Map– FlatMap– Sorted– Distinct– Limit
ints.stream() .map(i -> String.valueOf(i)) .reduce((s1, s2) -> s1 + ", " + s2) .get();
http://github.com/mjremijan http://slideshare.net/mjremijan
Terminal operations• Eager
– This is what starts the process
• Transform stream into something else– Collection/List– Map– Single value
• Examples– ForEach– Average– Count– Max– Min– Reduce
String str = ints .stream() .map(i -> String.valueOf(i)) .reduce((s1, s2) -> s1 + ", " + s2) .get();
– Collect– toArray– findFirst– findAny– anyMatch– allMatch
http://github.com/mjremijan http://slideshare.net/mjremijan
Specialized streams• Stream<T>
– Basis for starting all streaming operations
• Specialized Streams– IntStream– LongStream– DoubleStream
• Provide specialized terminal operations– average()– sum()– min()– max()– …
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: forEach• Terminal Operator• forEach
– Execute the lambda on each element of the stream
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: min & max• Specialized
Terminal Operator• min, max
– Returns the min or max element of the stream…maybe!
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: min & max (cont.)• Just Stream<T>
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: sum & average• Specialized
Terminal Operator• sum
– the total amount resulting from the addition of two or more numbers, amounts, or items.
• average– a number expressing the central or
typical value in a set of data, in particular the mode, median, or (most commonly) the mean, which is calculated by dividing the sum of the values in the set by their number.
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: sum & average (cont.)• Just Stream<T>• Sum
– Reduce to a single value
• Average– Can’t do it…directly.
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: reduce• Terminal Operator• reduce
– Turn all the stream elements into a single value of the same type
• Product of numbers– Multiply all the numbers
together– 3628800
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: sum of squares• Terminal Operator• Sum of squares
– Square each number then get the sum.
• Unfortunately wrong– 379
• 3 + (10*10) = 103• 103 + (6*6) = 139• 139 + (1*1) = 140• …
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: sum of squares (cont.)• Terminal Operator • Sum of squares• Correct!
– 385
• 0 + (3*3) = 9• 9 + (10*10) = 109• 109 + (6*6) = 145• …
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: CSV string• Terminal Operator • Comma Separated Values
– tabular data, each record consists of one or more values, separated by commas.
• Stream<String>– Needed to reduce to a single
String value
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: filter• Intermediate Operator• filter
– Filter stream elements by some test
– Resulting stream typically smaller than original
• Evens
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: odds• Intermediate Operator• Odds
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: primes• Intermediate Operator• Primes
– Kind of
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: sorted• Intermediate Operator• sorted
– Jumble stream items around into a different order
– Resulting stream has same number of elements as orginal
• Low-to-high
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: high-to-low• Intermediate Operator• High-to-low
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: in 4-8 and sorted• Intermediate Operator• Between 4-8 inclusive,
sorted in reverse order
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: map• Intermediate Operator• map
– Convert / map elements of the stream into something else.
– Resulting steam has same number of elements as original
• To squares
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: to halves• Intermediate Operator• To halves
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: to String• Intermediate Operator• To strings
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: to Widget• Intermediate Operator• Map to my own Widget
object
• Create Widget– Basic bean
http://github.com/mjremijan http://slideshare.net/mjremijan
• Intermediate Operator• To widgets
Example: to Widget (cont.)
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: Putting things together• How to translate your
processing into intermediate and terminal operations?
• Get all odds, square them, then sort low-to-high.
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: int to Invoice• Invoice ID values• Find invoices for the last 6
months of the year, sorted by highest billing amount to lowest.
• Create Invoice – Basic bean
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: int to Invoice (cont.)• Create InvoiceFinder
– Business logic to get invoices– SQL– Web Service– REST Service– etc…
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: int to Invoice (cont.)• Map• Filter• Sort• Collect
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: Beyond int• All examples so far
– Same array of int values
• int values are…– Boring?
• A Person is…– Interesting?
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: Beyond int (cont.) • Create PersonFinder
– Small database of person data
– Find All
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: max age• Find max age• Person::getAge
– Method Reference– Used to refer directly to an
existing method instead of creating a method with a lambda expression
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: in their 30’s• Find people in
their 30’s
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: 1st in Chicago• Find the first
person, listed alphabetically by last name, who lives in Chicago
http://github.com/mjremijan http://slideshare.net/mjremijan
Example: sort & sub-sort• List all people
sorted first by city then sub-sorted by last name reversed.
http://github.com/mjremijan http://slideshare.net/mjremijan
Summary• Lambda
– Brings functional programming to Java– Introduced in Java 8– Allow functions/methods to be used outside an Object
• Pass lambdas (methods) around
– Not objects!
• Stream<T>– New method of collection processing for Java– Introduced in Java 8– Heavily reliant on lambdas– Intermediate and terminal operations
http://github.com/mjremijan http://slideshare.net/mjremijan
Email regular expression
- http://emailregex.com/
Summary (cont.)• We just scratched the surface
– Can get much more complicated
• How do I learn more?– StackOverflow!
http://github.com/mjremijan http://slideshare.net/mjremijan
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
Top Related