SlideShare a Scribd company logo
© 1996-2017 All Rights Reserved.
https://youtu.be/tGaVyi57EZU
Java 8 Streams
Haim Michael
August 1st
, 2017
All logos, trade marks and brand names used in this presentation belong
to the respective owners.
lifemichael
© 1996-2017 All Rights Reserved.
Haim Michael Introduction
● Snowboarding. Learning. Coding. Teaching. More
than 16 years of Practical Experience.
lifemichael
© 1996-2017 All Rights Reserved.
Haim Michael Introduction
● Professional Certifications
Zend Certified Engineer in PHP
Certified Java Professional
Certified Java EE Web Component Developer
OMG Certified UML Professional
● MBA (cum laude) from Tel-Aviv University
Information Systems Management
lifemichael
© 1996-2017 All Rights Reserved.
Introduction
 Java 8 introduces the possibility to represent a
sequence of objects as a stream.
 Using streams we can process the sequence of
objects in a declarative way that leverages the
multicore architecture.
lifemichael
© 1996-2017 All Rights Reserved.
Stream of Collection
 The stream() method returns a sequential
stream composed of elements coming from a
collection.
lifemichael
© 1996-2017 All Rights Reserved.
Stream of Collection
package com.lifemichael.samples;
import java.util.function.*;
import java.util.*;
import java.util.stream.Stream;
public class Program {
public static void main(String[] args) {
List<Integer> numbers = new LinkedList<Integer>();
numbers.add(24);
numbers.add(13);
numbers.add(43);
numbers.add(45);
numbers.add(12);
Stream<Integer> stream = numbers.stream();
stream.filter(num->num%2==0).
forEach(num->System.out.println(num));
}
}
lifemichael
© 1996-2017 All Rights Reserved.
Stream of Collection
lifemichael
© 1996-2017 All Rights Reserved.
Stream of Array
 The stream() method that was defined in the
Arrays class allows us to create a stream out
of an array we hold.
lifemichael
© 1996-2017 All Rights Reserved.
Stream of Array
String[] cities = new String[]{"Rome",
"London",
"Moscow", "Ashdod", "Haifa", "Eilat",
"Zermatt"};
Stream<String> full = Arrays.
stream(cities);
Stream<String> partial = Arrays.
stream(cities, 1, 3);
full.forEach(str->System.out.println(str));
lifemichael
© 1996-2017 All Rights Reserved.
Building Streams
 Calling the builder static method in Stream
we get a Stream.Builder<T> object. Calling
builder we should specify the desired type,
otherwise we will get a builder for stream of
objects.
lifemichael
© 1996-2017 All Rights Reserved.
Building Streams
Stream.Builder<String> builder =
Stream.<String>builder();
Stream<String> stream = builder.
add("london").
add("Paris").
add("Zurich").build();
stream.forEach(str -> System.out.println(str));
lifemichael
© 1996-2017 All Rights Reserved.
Infinite Streams
 We can easily create infinite streams. We can
do it either using the Stream.generate() or
the Stream.iterate() functions.
lifemichael
© 1996-2017 All Rights Reserved.
Infinite Streams
 The Stream.generate static method receives a
Supplier<T> object, that generates endless
number of objects.
 If we don't want the Supplier<T> object to work
endlessly you better use the limit function in
order to limit the size of the generated stream.
lifemichael
© 1996-2017 All Rights Reserved.
Infinite Streams
Stream<String> stream =
Stream.generate(() -> String.
valueOf((int(100*Math.random()))).
limit(10);
stream.forEach(str -> System.out.println(str));
lifemichael
© 1996-2017 All Rights Reserved.
Infinite Streams
 The Stream.iterate static method provides
us with an alternative way for creating endless
streams. The first argument this method
receives is the first element of the stream it is
going to generate. The second argument is an
UnaryOperator object.
lifemichael
© 1996-2017 All Rights Reserved.
Infinite Streams
 If we don't want to get endless stream till the
memory ends we better use the limit function
in order to limit it.
lifemichael
© 1996-2017 All Rights Reserved.
Infinite Streams
Stream<Integer> stream = Stream.
iterate(10, n -> n+5).
limit(10);
stream.forEach(data -> System.out.println(data));
lifemichael
© 1996-2017 All Rights Reserved.
Empty Streams
 The empty() method was defined as a static
method in Stream.
 Calling this method we will get an empty stream.
It is a useful method when developing a method
that should return a reference for a Stream
object. Instead of returning null we can easily
return an empty stream.
lifemichael
© 1996-2017 All Rights Reserved.
Empty Streams
public class Main {
public static void main(String[] args) {
List<String> ob = null;
Stream stream = streamOf(ob);
}
public static Stream<String> streamOf(List<String> list) {
return list == null || list.isEmpty() ? Stream.empty() :
list.stream();
}
}
lifemichael
© 1996-2017 All Rights Reserved.
Stream of Primitives
 We can create streams out of three primitive
types: int, long and double. In order to allow
that, three new special interfaces were created:
IntStream, LongStream, DoubleStream.
 Each one of these three interfaces include the
definition of static methods that generates
various streams of the specific primitive type
the interface serves .
lifemichael
© 1996-2017 All Rights Reserved.
Stream of Primitives
IntStream ints = IntStream.range(1, 12);
ints.forEach(num->System.out.println(num));
lifemichael
© 1996-2017 All Rights Reserved.
Stream of Random Numbers
 The Random class has the doubles method that
generates randomly generates values of the type
double.
lifemichael
© 1996-2017 All Rights Reserved.
Stream of Random Numbers
Random random = new Random();
DoubleStream stream = random.doubles(10);
stream.forEach(num->System.out.println("number="+num));
lifemichael
© 1996-2017 All Rights Reserved.
Stream of Chars
 Strings can also be used as a source for creating
a stream. Using the chars() method of the
String class we can get a stream of chars.
Since the Java API doesn't have the
CharStream, we will use the IntStream instead.
lifemichael
© 1996-2017 All Rights Reserved.
Stream of Chars
IntStream stream = "abc".chars();
stream.forEach((tav->System.out.print((char)tav)));
lifemichael
© 1996-2017 All Rights Reserved.
Stream of File
 The Files class allows to generate a
Stream<String> of a text file using the
lines() method. Every line of the text
becomes an element of the stream.
lifemichael
© 1996-2017 All Rights Reserved.
Stream of File
Path path = Paths.get("./file.txt");
Stream<String> stream = Files.lines(path);
stream.forEach(str->System.out.println(str));
lifemichael
© 1996-2017 All Rights Reserved.
Streams Cannot Be Reused
 Once a terminal operation was executed the
stream will become inaccessible. It won't be
possible to iterate it again.
 This behavior makes sense. Streams were
designed to provide an ability to apply a finite
sequence of operations on a series of elements
coming from a specific store. Streams weren't
created for storing elements.
lifemichael
© 1996-2017 All Rights Reserved.
The parallelStream() Method
 The parallelStream() method returns a
parallel stream. Getting a parallel is not
guaranteed. We shall get a parallel stream if
possible only.
 This method returns a reference for object of the
type Stream.
lifemichael
© 1996-2017 All Rights Reserved.
The parallelStream()Method
package com.lifemichael.samples;
import java.util.function.*;
import java.util.*;
import java.util.stream.Stream;
public class Program {
public static void main(String[] args) {
List<Integer> numbers = new LinkedList<Integer>();
numbers.add(24);
numbers.add(13);
numbers.add(43);
numbers.add(45);
numbers.add(12);
Stream<Integer> stream = numbers.parallelStream();
stream.filter(num->num%2==0).
forEach(num->System.out.println(num));
}
}
lifemichael
© 1996-2017 All Rights Reserved.
The parallelStream() Method
lifemichael
© 1996-2017 All Rights Reserved.
The forEach() Method
 Using this method we can iterate the elements our
stream includes.
lifemichael
© 1996-2017 All Rights Reserved.
The forEach() Method
package com.lifemichael.samples;
import java.util.function.*;
import java.util.*;
import java.util.stream.Stream;
public class Program {
public static void main(String[] args) {
new Random().
ints().limit(10).forEach(System.out::println);
}
}
lifemichael
© 1996-2017 All Rights Reserved.
The forEach() Method
lifemichael
© 1996-2017 All Rights Reserved.
The map() Method
 Using this method we map each element with a
new one calculated based on the first.
lifemichael
© 1996-2017 All Rights Reserved.
The map() Method
public class Program {
public static void main(String[] args) {
List<Integer> list = new LinkedList();
list.add(12);
list.add(54);
list.add(53);
list.add(65);
list.add(72);
list.stream().map(n->n*n).
filter(num->num%2==0).distinct().
forEach(System.out::println);
}
}
lifemichael
© 1996-2017 All Rights Reserved.
The map() Method
lifemichael
© 1996-2017 All Rights Reserved.
The filter() Method
 Using this method we can filter our stream
taking out all elements that don't meet our
criteria.
lifemichael
© 1996-2017 All Rights Reserved.
The filter() Method
public class FilterDemo {
public static void main(String[] args) {
List<Integer> list = new LinkedList();
list.add(12);
list.add(54);
list.add(53);
list.add(65);
list.add(72);
list.stream().
filter(num->num%2==0).
forEach(System.out::println);
}
}
lifemichael
© 1996-2017 All Rights Reserved.
The filter() Method
lifemichael
© 1996-2017 All Rights Reserved.
The sorted() Method
 Using this method we can sort our stream.
There are two versions for this method. The
first one sorts the elements in according with
their natural order. The second one has a
second parameter of the Comparator type.
lifemichael
© 1996-2017 All Rights Reserved.
The sorted() Method
public class Program {
public static void main(String[] args) {
List<Integer> list = new LinkedList();
list.add(12);
list.add(54);
list.add(53);
list.add(65);
list.add(72);
list.add(8);
list.stream().sorted().
forEach(System.out::println);
}
}
lifemichael
© 1996-2017 All Rights Reserved.
The sorted() Method
lifemichael
© 1996-2017 All Rights Reserved.
Streams Pipeline
 In order to perform a sequence of operations
over the elements coming from a specific data
source and aggregate their results, three parts
are needed. The source, the intermediate
operation(s) and the terminal operation.
 The intermediate operations return a new
modified stream.
lifemichael
© 1996-2017 All Rights Reserved.
Streams Pipeline
 If more than one modification is needed,
intermediate operations can be chained with
each other.
 Only one terminal operation can be used per
stream. The forEach method is a terminal
operation.
lifemichael
© 1996-2017 All Rights Reserved.
Streams Pipeline
IntStream ints = IntStream.range(-100, 101);
ints.filter(number->number%2==0).
filter(number->number>0).
filter(number->number%3==0).
map(number->2*number).
forEach(num->System.out.println(num));
lifemichael
© 1996-2017 All Rights Reserved.
Lazy Invocation
 The intermediate operations are lazy. They will
be invoked only if necessary in order to allow
the terminal operation to execute.
lifemichael
© 1996-2017 All Rights Reserved.
Lazy Invocation
System.out.println("counter="+counter);
IntStream ints = IntStream.range(-100, 101);
IntStream ints2 = ints.filter(number->number%2==0).
filter(number->{
counter++;
return number>0;
}).
filter(number->number%3==0).
map(number->2*number);
System.out.println("counter="+counter);
System.out.println("number of elements is "+ints2.count());
System.out.println("counter="+counter);
lifemichael
© 1996-2017 All Rights Reserved.
Lazy Invocation
lifemichael
© 1996-2017 All Rights Reserved.
Order of Execution
 The right order is one of the most important
aspects of chaining operations in the stream
pipeline.The intermediate operations that
reduce the size of the stream should be placed
before the operations that apply each element.
Methods, such as filter(), skip() and
distinct() better be in the beginning of the
chain. This way the performance will improve.
lifemichael
© 1996-2017 All Rights Reserved.
Stream Reduction
 The API allows us to customize the Stream’s
reduction mechanism. The reduce() and the
collect() methods allows us to do so
lifemichael
© 1996-2017 All Rights Reserved.
Stream Reduction
 The reduce() method was defined in several versions.
identity - this is the initial value that will be added to each element. If
the stream is empty then Identity will be the result.
accumulator - this is the aggregation function. It is the logic by which
the aggregation takes place. each step it creates a new value.
combiner - this is the function that aggregates the results of the
accumulator. It is called in parallel mode to reduce accumulator results
coming from separated threads.
© 1996-2017 All Rights Reserved.
Stream Reduction
Optional<T> reduce(BinaryOperator<T> accumulator)
This method performs a reduction on the elements of this
stream, using an associative accumulation function, and
returns an Optional object describing the reduced value,
if any.
OptionalInt reduced = IntStream.range(1, 5).
reduce((a, b) -> a + b);
System.out.println(reduced.getAsInt());
© 1996-2017 All Rights Reserved.
Stream Reduction
<U> U reduce(U identity,
BiFunction<U,? super T,U> accumulator,
BinaryOperator<U> combiner)
This method performs a reduction on the elements of this stream,
using the provided identity, accumulation and combining functions.
int reducedParallel = Arrays.asList(1, 2, 3, 4, 9).parallelStream()
.<Integer>reduce(10, (a, b) -> a + b, (a, b) -> {
System.out.println("combiner is working");
return a + b;
});
System.out.println("result="+reducedParallel);
© 1996-2017 All Rights Reserved.
Stream Reduction
 The collect() method receives an argument
of the Collector type, that specified the
mechanism of reduction. There are already few
Collector types we can access using the
Collectors class.
lifemichael
© 1996-2017 All Rights Reserved.
Stream Reduction
class Product
{
private int weight;
private String name;
public Product(int weight, String name) {
this.setWeight(weight);
this.setName(name);
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
lifemichael
© 1996-2017 All Rights Reserved.
Stream Reduction
public static void main(String[] args) {
List<Product> products = Arrays.asList(new Product(33, "potatoes"),
new Product(13, "oranges"), new Product(23, "pepper"),
new Product(13, "chcolate"), new Product(23, "coffee"),
new Product(20, "bread"), new Product(12, "sugar"));
List<String> names = products.
stream().map(Product::getName).
collect(Collectors.toList());
System.out.println(names);
String str = products.stream().map(Product::getName).
collect(Collectors.
joining(", ", "###[ ", " ]###"));
System.out.println(str);
© 1996-2017 All Rights Reserved.
Stream Reduction
int total = products.stream().
collect(Collectors.summingInt(Product::getWeight));
System.out.println(total);
IntSummaryStatistics statistics = products.stream().
collect(Collectors.summarizingInt(Product::getWeight));
System.out.println(statistics);
}
© 1996-2017 All Rights Reserved.
Parallel Streams
 Under the hood, the Stream API automatically
uses the ForkJoin framework to execute
operations in parallel. The common thread
pool will be used.
lifemichael
© 1996-2017 All Rights Reserved.
Parallel Streams
 When using the parallel mode we better make
sure that the tasks executed on separated
threads need similar amount of time.
Otherwise, if one task lasts much longer than
the other, it might slow down the entire
program.
lifemichael
© 1996-2017 All Rights Reserved.
lifemichael
Questions & Answers
If you enjoyed my lecture please leave me a comment
at http://speakerpedia.com/speakers/life-michael.
Thanks for your time!
Haim.
© Haim Michael 2017. All Rights Reserved.
Questions & Answers
● If you enjoyed my lecture please leave me a comment
at http://speakerpedia.com/speakers/life-michael.
Thanks for your time!
Haim.
LifeMichael.com
© Haim Michael 2017. All Rights Reserved.
Questions & Answers
● If you enjoyed my lecture please leave me a comment
at http://speakerpedia.com/speakers/life-michael.
Thanks for your time!
Haim.
LifeMichael.com

More Related Content

What's hot (20)

PDF
JAVA NIO
오석 한
 
PPSX
OOP with Java - Continued
Hitesh-Java
 
PPT
Java 8 Streams
Manvendra Singh
 
PDF
[COSCUP 2022] 讓黑畫面再次偉大 - 用 PHP 寫 CLI 工具
Shengyou Fan
 
PDF
Java 8 Lambda Expressions
Scott Leberknight
 
PDF
Collections in Java Notes
Shalabh Chaudhary
 
PPT
Java IO Streams V4
Sunil OS
 
PDF
HTML5--The 30,000' View (A fast-paced overview of HTML5)
Peter Lubbers
 
PPTX
Introduction to java 8 stream api
Vladislav sidlyarevich
 
PPTX
Java String
SATYAM SHRIVASTAV
 
PPT
Java multi threading
Raja Sekhar
 
PPT
DJango
Sunil OS
 
ODP
Postgrest: the REST API for PostgreSQL databases
Lucio Grenzi
 
PPT
Collections Framework
Sunil OS
 
PPTX
Python basics
RANAALIMAJEEDRAJPUT
 
PDF
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
PPT
JDBC
Sunil OS
 
PDF
Java Deserialization Vulnerabilities - The Forgotten Bug Class
CODE WHITE GmbH
 
JAVA NIO
오석 한
 
OOP with Java - Continued
Hitesh-Java
 
Java 8 Streams
Manvendra Singh
 
[COSCUP 2022] 讓黑畫面再次偉大 - 用 PHP 寫 CLI 工具
Shengyou Fan
 
Java 8 Lambda Expressions
Scott Leberknight
 
Collections in Java Notes
Shalabh Chaudhary
 
Java IO Streams V4
Sunil OS
 
HTML5--The 30,000' View (A fast-paced overview of HTML5)
Peter Lubbers
 
Introduction to java 8 stream api
Vladislav sidlyarevich
 
Java String
SATYAM SHRIVASTAV
 
Java multi threading
Raja Sekhar
 
DJango
Sunil OS
 
Postgrest: the REST API for PostgreSQL databases
Lucio Grenzi
 
Collections Framework
Sunil OS
 
Python basics
RANAALIMAJEEDRAJPUT
 
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
JDBC
Sunil OS
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class
CODE WHITE GmbH
 

Similar to Java 8 Streams - in Depth (20)

PPTX
Java Advanced Topic - Streams Presentations
MuraliD32
 
PPTX
JDK8 Streams
Bansilal Haudakari
 
PDF
Streams in Java 8
Tobias Coetzee
 
PPTX
Java se 8 streams pt1
Lars Lemos
 
PPTX
Lambdas And Streams Hands On Lab, JavaOne 2014
Simon Ritter
 
PDF
Charles Sharp: Java 8 Streams
jessitron
 
PDF
Java 8 Stream API (Valdas Zigas)
Kaunas Java User Group
 
PPTX
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Harmeet Singh(Taara)
 
PDF
Going reactive in java
José Paumard
 
PPTX
A Brief Conceptual Introduction to Functional Java 8 and its API
Jörn Guy Süß JGS
 
PDF
JDK8: Stream style
Sergey Kuksenko
 
PDF
Java Streams Interview short reminder with examples
Mark Papis
 
PDF
Sailing with Java 8 Streams
Ganesh Samarthyam
 
PPTX
Java 8 streams
Manav Prasad
 
PDF
Harnessing the Power of Java 8 Streams
IndicThreads
 
PDF
Lambda.pdf
ManishWalia18
 
PDF
Java Lambda internals with invoke dynamic
Mohit Kumar
 
PDF
Collectors in the Wild
José Paumard
 
PDF
Lambdas And Streams Hands On Lab
Simon Ritter
 
PDF
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
PROIDEA
 
Java Advanced Topic - Streams Presentations
MuraliD32
 
JDK8 Streams
Bansilal Haudakari
 
Streams in Java 8
Tobias Coetzee
 
Java se 8 streams pt1
Lars Lemos
 
Lambdas And Streams Hands On Lab, JavaOne 2014
Simon Ritter
 
Charles Sharp: Java 8 Streams
jessitron
 
Java 8 Stream API (Valdas Zigas)
Kaunas Java User Group
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Harmeet Singh(Taara)
 
Going reactive in java
José Paumard
 
A Brief Conceptual Introduction to Functional Java 8 and its API
Jörn Guy Süß JGS
 
JDK8: Stream style
Sergey Kuksenko
 
Java Streams Interview short reminder with examples
Mark Papis
 
Sailing with Java 8 Streams
Ganesh Samarthyam
 
Java 8 streams
Manav Prasad
 
Harnessing the Power of Java 8 Streams
IndicThreads
 
Lambda.pdf
ManishWalia18
 
Java Lambda internals with invoke dynamic
Mohit Kumar
 
Collectors in the Wild
José Paumard
 
Lambdas And Streams Hands On Lab
Simon Ritter
 
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
PROIDEA
 
Ad

More from Haim Michael (20)

PDF
The Visitor Classic Design Pattern [Free Meetup]
Haim Michael
 
PDF
Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]
Haim Michael
 
PDF
Introduction to Pattern Matching in Java [Free Meetup]
Haim Michael
 
PDF
Mastering The Collections in JavaScript [Free Meetup]
Haim Michael
 
PDF
Beyond Java - Evolving to Scala and Kotlin
Haim Michael
 
PDF
JavaScript Promises Simplified [Free Meetup]
Haim Michael
 
PDF
Scala Jump Start [Free Online Meetup in English]
Haim Michael
 
PDF
The MVVM Architecture in Java [Free Meetup]
Haim Michael
 
PDF
Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Haim Michael
 
PDF
Anti Patterns
Haim Michael
 
PDF
Virtual Threads in Java
Haim Michael
 
PDF
MongoDB Design Patterns
Haim Michael
 
PDF
Introduction to SQL Injections
Haim Michael
 
PDF
Record Classes in Java
Haim Michael
 
PDF
Microservices Design Patterns
Haim Michael
 
PDF
Structural Pattern Matching in Python
Haim Michael
 
PDF
Unit Testing in Python
Haim Michael
 
PDF
OOP Best Practices in JavaScript
Haim Michael
 
PDF
Java Jump Start
Haim Michael
 
PDF
JavaScript Jump Start 20220214
Haim Michael
 
The Visitor Classic Design Pattern [Free Meetup]
Haim Michael
 
Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]
Haim Michael
 
Introduction to Pattern Matching in Java [Free Meetup]
Haim Michael
 
Mastering The Collections in JavaScript [Free Meetup]
Haim Michael
 
Beyond Java - Evolving to Scala and Kotlin
Haim Michael
 
JavaScript Promises Simplified [Free Meetup]
Haim Michael
 
Scala Jump Start [Free Online Meetup in English]
Haim Michael
 
The MVVM Architecture in Java [Free Meetup]
Haim Michael
 
Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Haim Michael
 
Anti Patterns
Haim Michael
 
Virtual Threads in Java
Haim Michael
 
MongoDB Design Patterns
Haim Michael
 
Introduction to SQL Injections
Haim Michael
 
Record Classes in Java
Haim Michael
 
Microservices Design Patterns
Haim Michael
 
Structural Pattern Matching in Python
Haim Michael
 
Unit Testing in Python
Haim Michael
 
OOP Best Practices in JavaScript
Haim Michael
 
Java Jump Start
Haim Michael
 
JavaScript Jump Start 20220214
Haim Michael
 
Ad

Recently uploaded (20)

PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PPTX
Engineering the Java Web Application (MVC)
abhishekoza1981
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
PPTX
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
PPTX
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
PPTX
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PDF
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
Engineering the Java Web Application (MVC)
abhishekoza1981
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 

Java 8 Streams - in Depth

  • 1. © 1996-2017 All Rights Reserved. https://youtu.be/tGaVyi57EZU Java 8 Streams Haim Michael August 1st , 2017 All logos, trade marks and brand names used in this presentation belong to the respective owners. lifemichael
  • 2. © 1996-2017 All Rights Reserved. Haim Michael Introduction ● Snowboarding. Learning. Coding. Teaching. More than 16 years of Practical Experience. lifemichael
  • 3. © 1996-2017 All Rights Reserved. Haim Michael Introduction ● Professional Certifications Zend Certified Engineer in PHP Certified Java Professional Certified Java EE Web Component Developer OMG Certified UML Professional ● MBA (cum laude) from Tel-Aviv University Information Systems Management lifemichael
  • 4. © 1996-2017 All Rights Reserved. Introduction  Java 8 introduces the possibility to represent a sequence of objects as a stream.  Using streams we can process the sequence of objects in a declarative way that leverages the multicore architecture. lifemichael
  • 5. © 1996-2017 All Rights Reserved. Stream of Collection  The stream() method returns a sequential stream composed of elements coming from a collection. lifemichael
  • 6. © 1996-2017 All Rights Reserved. Stream of Collection package com.lifemichael.samples; import java.util.function.*; import java.util.*; import java.util.stream.Stream; public class Program { public static void main(String[] args) { List<Integer> numbers = new LinkedList<Integer>(); numbers.add(24); numbers.add(13); numbers.add(43); numbers.add(45); numbers.add(12); Stream<Integer> stream = numbers.stream(); stream.filter(num->num%2==0). forEach(num->System.out.println(num)); } } lifemichael
  • 7. © 1996-2017 All Rights Reserved. Stream of Collection lifemichael
  • 8. © 1996-2017 All Rights Reserved. Stream of Array  The stream() method that was defined in the Arrays class allows us to create a stream out of an array we hold. lifemichael
  • 9. © 1996-2017 All Rights Reserved. Stream of Array String[] cities = new String[]{"Rome", "London", "Moscow", "Ashdod", "Haifa", "Eilat", "Zermatt"}; Stream<String> full = Arrays. stream(cities); Stream<String> partial = Arrays. stream(cities, 1, 3); full.forEach(str->System.out.println(str)); lifemichael
  • 10. © 1996-2017 All Rights Reserved. Building Streams  Calling the builder static method in Stream we get a Stream.Builder<T> object. Calling builder we should specify the desired type, otherwise we will get a builder for stream of objects. lifemichael
  • 11. © 1996-2017 All Rights Reserved. Building Streams Stream.Builder<String> builder = Stream.<String>builder(); Stream<String> stream = builder. add("london"). add("Paris"). add("Zurich").build(); stream.forEach(str -> System.out.println(str)); lifemichael
  • 12. © 1996-2017 All Rights Reserved. Infinite Streams  We can easily create infinite streams. We can do it either using the Stream.generate() or the Stream.iterate() functions. lifemichael
  • 13. © 1996-2017 All Rights Reserved. Infinite Streams  The Stream.generate static method receives a Supplier<T> object, that generates endless number of objects.  If we don't want the Supplier<T> object to work endlessly you better use the limit function in order to limit the size of the generated stream. lifemichael
  • 14. © 1996-2017 All Rights Reserved. Infinite Streams Stream<String> stream = Stream.generate(() -> String. valueOf((int(100*Math.random()))). limit(10); stream.forEach(str -> System.out.println(str)); lifemichael
  • 15. © 1996-2017 All Rights Reserved. Infinite Streams  The Stream.iterate static method provides us with an alternative way for creating endless streams. The first argument this method receives is the first element of the stream it is going to generate. The second argument is an UnaryOperator object. lifemichael
  • 16. © 1996-2017 All Rights Reserved. Infinite Streams  If we don't want to get endless stream till the memory ends we better use the limit function in order to limit it. lifemichael
  • 17. © 1996-2017 All Rights Reserved. Infinite Streams Stream<Integer> stream = Stream. iterate(10, n -> n+5). limit(10); stream.forEach(data -> System.out.println(data)); lifemichael
  • 18. © 1996-2017 All Rights Reserved. Empty Streams  The empty() method was defined as a static method in Stream.  Calling this method we will get an empty stream. It is a useful method when developing a method that should return a reference for a Stream object. Instead of returning null we can easily return an empty stream. lifemichael
  • 19. © 1996-2017 All Rights Reserved. Empty Streams public class Main { public static void main(String[] args) { List<String> ob = null; Stream stream = streamOf(ob); } public static Stream<String> streamOf(List<String> list) { return list == null || list.isEmpty() ? Stream.empty() : list.stream(); } } lifemichael
  • 20. © 1996-2017 All Rights Reserved. Stream of Primitives  We can create streams out of three primitive types: int, long and double. In order to allow that, three new special interfaces were created: IntStream, LongStream, DoubleStream.  Each one of these three interfaces include the definition of static methods that generates various streams of the specific primitive type the interface serves . lifemichael
  • 21. © 1996-2017 All Rights Reserved. Stream of Primitives IntStream ints = IntStream.range(1, 12); ints.forEach(num->System.out.println(num)); lifemichael
  • 22. © 1996-2017 All Rights Reserved. Stream of Random Numbers  The Random class has the doubles method that generates randomly generates values of the type double. lifemichael
  • 23. © 1996-2017 All Rights Reserved. Stream of Random Numbers Random random = new Random(); DoubleStream stream = random.doubles(10); stream.forEach(num->System.out.println("number="+num)); lifemichael
  • 24. © 1996-2017 All Rights Reserved. Stream of Chars  Strings can also be used as a source for creating a stream. Using the chars() method of the String class we can get a stream of chars. Since the Java API doesn't have the CharStream, we will use the IntStream instead. lifemichael
  • 25. © 1996-2017 All Rights Reserved. Stream of Chars IntStream stream = "abc".chars(); stream.forEach((tav->System.out.print((char)tav))); lifemichael
  • 26. © 1996-2017 All Rights Reserved. Stream of File  The Files class allows to generate a Stream<String> of a text file using the lines() method. Every line of the text becomes an element of the stream. lifemichael
  • 27. © 1996-2017 All Rights Reserved. Stream of File Path path = Paths.get("./file.txt"); Stream<String> stream = Files.lines(path); stream.forEach(str->System.out.println(str)); lifemichael
  • 28. © 1996-2017 All Rights Reserved. Streams Cannot Be Reused  Once a terminal operation was executed the stream will become inaccessible. It won't be possible to iterate it again.  This behavior makes sense. Streams were designed to provide an ability to apply a finite sequence of operations on a series of elements coming from a specific store. Streams weren't created for storing elements. lifemichael
  • 29. © 1996-2017 All Rights Reserved. The parallelStream() Method  The parallelStream() method returns a parallel stream. Getting a parallel is not guaranteed. We shall get a parallel stream if possible only.  This method returns a reference for object of the type Stream. lifemichael
  • 30. © 1996-2017 All Rights Reserved. The parallelStream()Method package com.lifemichael.samples; import java.util.function.*; import java.util.*; import java.util.stream.Stream; public class Program { public static void main(String[] args) { List<Integer> numbers = new LinkedList<Integer>(); numbers.add(24); numbers.add(13); numbers.add(43); numbers.add(45); numbers.add(12); Stream<Integer> stream = numbers.parallelStream(); stream.filter(num->num%2==0). forEach(num->System.out.println(num)); } } lifemichael
  • 31. © 1996-2017 All Rights Reserved. The parallelStream() Method lifemichael
  • 32. © 1996-2017 All Rights Reserved. The forEach() Method  Using this method we can iterate the elements our stream includes. lifemichael
  • 33. © 1996-2017 All Rights Reserved. The forEach() Method package com.lifemichael.samples; import java.util.function.*; import java.util.*; import java.util.stream.Stream; public class Program { public static void main(String[] args) { new Random(). ints().limit(10).forEach(System.out::println); } } lifemichael
  • 34. © 1996-2017 All Rights Reserved. The forEach() Method lifemichael
  • 35. © 1996-2017 All Rights Reserved. The map() Method  Using this method we map each element with a new one calculated based on the first. lifemichael
  • 36. © 1996-2017 All Rights Reserved. The map() Method public class Program { public static void main(String[] args) { List<Integer> list = new LinkedList(); list.add(12); list.add(54); list.add(53); list.add(65); list.add(72); list.stream().map(n->n*n). filter(num->num%2==0).distinct(). forEach(System.out::println); } } lifemichael
  • 37. © 1996-2017 All Rights Reserved. The map() Method lifemichael
  • 38. © 1996-2017 All Rights Reserved. The filter() Method  Using this method we can filter our stream taking out all elements that don't meet our criteria. lifemichael
  • 39. © 1996-2017 All Rights Reserved. The filter() Method public class FilterDemo { public static void main(String[] args) { List<Integer> list = new LinkedList(); list.add(12); list.add(54); list.add(53); list.add(65); list.add(72); list.stream(). filter(num->num%2==0). forEach(System.out::println); } } lifemichael
  • 40. © 1996-2017 All Rights Reserved. The filter() Method lifemichael
  • 41. © 1996-2017 All Rights Reserved. The sorted() Method  Using this method we can sort our stream. There are two versions for this method. The first one sorts the elements in according with their natural order. The second one has a second parameter of the Comparator type. lifemichael
  • 42. © 1996-2017 All Rights Reserved. The sorted() Method public class Program { public static void main(String[] args) { List<Integer> list = new LinkedList(); list.add(12); list.add(54); list.add(53); list.add(65); list.add(72); list.add(8); list.stream().sorted(). forEach(System.out::println); } } lifemichael
  • 43. © 1996-2017 All Rights Reserved. The sorted() Method lifemichael
  • 44. © 1996-2017 All Rights Reserved. Streams Pipeline  In order to perform a sequence of operations over the elements coming from a specific data source and aggregate their results, three parts are needed. The source, the intermediate operation(s) and the terminal operation.  The intermediate operations return a new modified stream. lifemichael
  • 45. © 1996-2017 All Rights Reserved. Streams Pipeline  If more than one modification is needed, intermediate operations can be chained with each other.  Only one terminal operation can be used per stream. The forEach method is a terminal operation. lifemichael
  • 46. © 1996-2017 All Rights Reserved. Streams Pipeline IntStream ints = IntStream.range(-100, 101); ints.filter(number->number%2==0). filter(number->number>0). filter(number->number%3==0). map(number->2*number). forEach(num->System.out.println(num)); lifemichael
  • 47. © 1996-2017 All Rights Reserved. Lazy Invocation  The intermediate operations are lazy. They will be invoked only if necessary in order to allow the terminal operation to execute. lifemichael
  • 48. © 1996-2017 All Rights Reserved. Lazy Invocation System.out.println("counter="+counter); IntStream ints = IntStream.range(-100, 101); IntStream ints2 = ints.filter(number->number%2==0). filter(number->{ counter++; return number>0; }). filter(number->number%3==0). map(number->2*number); System.out.println("counter="+counter); System.out.println("number of elements is "+ints2.count()); System.out.println("counter="+counter); lifemichael
  • 49. © 1996-2017 All Rights Reserved. Lazy Invocation lifemichael
  • 50. © 1996-2017 All Rights Reserved. Order of Execution  The right order is one of the most important aspects of chaining operations in the stream pipeline.The intermediate operations that reduce the size of the stream should be placed before the operations that apply each element. Methods, such as filter(), skip() and distinct() better be in the beginning of the chain. This way the performance will improve. lifemichael
  • 51. © 1996-2017 All Rights Reserved. Stream Reduction  The API allows us to customize the Stream’s reduction mechanism. The reduce() and the collect() methods allows us to do so lifemichael
  • 52. © 1996-2017 All Rights Reserved. Stream Reduction  The reduce() method was defined in several versions. identity - this is the initial value that will be added to each element. If the stream is empty then Identity will be the result. accumulator - this is the aggregation function. It is the logic by which the aggregation takes place. each step it creates a new value. combiner - this is the function that aggregates the results of the accumulator. It is called in parallel mode to reduce accumulator results coming from separated threads.
  • 53. © 1996-2017 All Rights Reserved. Stream Reduction Optional<T> reduce(BinaryOperator<T> accumulator) This method performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional object describing the reduced value, if any. OptionalInt reduced = IntStream.range(1, 5). reduce((a, b) -> a + b); System.out.println(reduced.getAsInt());
  • 54. © 1996-2017 All Rights Reserved. Stream Reduction <U> U reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner) This method performs a reduction on the elements of this stream, using the provided identity, accumulation and combining functions. int reducedParallel = Arrays.asList(1, 2, 3, 4, 9).parallelStream() .<Integer>reduce(10, (a, b) -> a + b, (a, b) -> { System.out.println("combiner is working"); return a + b; }); System.out.println("result="+reducedParallel);
  • 55. © 1996-2017 All Rights Reserved. Stream Reduction  The collect() method receives an argument of the Collector type, that specified the mechanism of reduction. There are already few Collector types we can access using the Collectors class. lifemichael
  • 56. © 1996-2017 All Rights Reserved. Stream Reduction class Product { private int weight; private String name; public Product(int weight, String name) { this.setWeight(weight); this.setName(name); } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } public String getName() { return name; } public void setName(String name) { this.name = name; } } lifemichael
  • 57. © 1996-2017 All Rights Reserved. Stream Reduction public static void main(String[] args) { List<Product> products = Arrays.asList(new Product(33, "potatoes"), new Product(13, "oranges"), new Product(23, "pepper"), new Product(13, "chcolate"), new Product(23, "coffee"), new Product(20, "bread"), new Product(12, "sugar")); List<String> names = products. stream().map(Product::getName). collect(Collectors.toList()); System.out.println(names); String str = products.stream().map(Product::getName). collect(Collectors. joining(", ", "###[ ", " ]###")); System.out.println(str);
  • 58. © 1996-2017 All Rights Reserved. Stream Reduction int total = products.stream(). collect(Collectors.summingInt(Product::getWeight)); System.out.println(total); IntSummaryStatistics statistics = products.stream(). collect(Collectors.summarizingInt(Product::getWeight)); System.out.println(statistics); }
  • 59. © 1996-2017 All Rights Reserved. Parallel Streams  Under the hood, the Stream API automatically uses the ForkJoin framework to execute operations in parallel. The common thread pool will be used. lifemichael
  • 60. © 1996-2017 All Rights Reserved. Parallel Streams  When using the parallel mode we better make sure that the tasks executed on separated threads need similar amount of time. Otherwise, if one task lasts much longer than the other, it might slow down the entire program. lifemichael
  • 61. © 1996-2017 All Rights Reserved. lifemichael Questions & Answers If you enjoyed my lecture please leave me a comment at http://speakerpedia.com/speakers/life-michael. Thanks for your time! Haim.
  • 62. © Haim Michael 2017. All Rights Reserved. Questions & Answers ● If you enjoyed my lecture please leave me a comment at http://speakerpedia.com/speakers/life-michael. Thanks for your time! Haim. LifeMichael.com
  • 63. © Haim Michael 2017. All Rights Reserved. Questions & Answers ● If you enjoyed my lecture please leave me a comment at http://speakerpedia.com/speakers/life-michael. Thanks for your time! Haim. LifeMichael.com