SlideShare ist ein Scribd-Unternehmen logo
1 von 27
Downloaden Sie, um offline zu lesen
Stream API
Valdas Žigas · kaunas.jug@gmail.com · www.kaunas-jug.lt
{ λ }
Java 8
Valdas Žigas
● 13.6 x JAVA
● KTU Programų inžinerija
● SCJP 1.5, PL/SQL OCA
● Oracle University Delivery Instructor
● LKSoft, BPI, Infor, Affecto. PSE, uTrack
Presentation Source Code
https://github.com/valdasz/kaunasjug3streamapi.git
Java 8 { λ }. Impression
List<Long> idList = new ArrayList<>();
...
idList.stream().distinct().map(EmployeeStreamMain::
findById).filter(e -> e != null).filter(e -> e.getSalary() >
40000).findFirst().orElse(null);
Java 8 { λ }. Impression
12 Years Without Lambdas ...
java.util.stream.Stream<T>
A sequence of elements supporting sequential
and parallel bulk operations
public interface Stream<T> extends BaseStream<T,
Stream<T>>
public interface BaseStream<T, S extends BaseStream<T,
S>> extends AutoCloseable
java.util.stream.BaseStream<T>
Simple example. forEach
List<String> pronouns = Arrays.asList("i", "you", "he", "she", "it", "we", "you", "they");
pronouns.stream().forEach(p ->
System.out.println(p));
StreamFromListSimpleForEach.java
Simple example. forEach. Old school
List<String> pronouns = Arrays.asList("i", "you", "he", "she", "it", "we", "you",
"they");
pronouns.stream().forEach(new Consumer<String>() {
public void accept(String p) {
System.out.println(p);
}
});
StreamFromListSimpleForEachOldStyle.java
Simple example. filter
List<String> pronouns = Arrays.asList("i", "you", "he", "she", "it", "we", "you",
"they");
pronouns.stream().distinct().filter(p -> p.length() == 3).forEach(p ->
System.out.println(p));
StreamFromListSimpleFilter.java
Simple example. filter. Old school
pronouns.stream().distinct().filter(new Predicate<String>() {
public boolean test(String p) {
return p.length() == 3;
}
}).forEach(new Consumer<String>() {
public void accept(String p) {
System.out.println(p);
}}); StreamFromListSimpleFilterOldStyle.java
● Collection.stream(),
Collection.parallelStream()
● Arrays.stream(T[])
● Stream.of(T...)
● IntStream.range(int, int)
● Stream.iterate(T,
UnaryOperator<T>)
Creating streams
Creating streams. Arrays.stream
Arrays.stream(new String[] { "This", "is", "Java8", "Stream" })
.forEach(System.out::println);
Arrays.stream(new Integer[] { 1, 2, 3 }).forEach(System.out::println);
Arrays.stream(new int[] { 1, 2, 3 }).forEach(System.out::println);
StreamFromArraysStream.java
Creating streams. Stream.of
Stream.of("This", "is", "Java8", "Stream").forEach(System.out::println);
Stream.of(new Integer[] { 1, 2, 3 }).forEach(System.out::println);
Stream.of(new int[] { 1, 2, 3 }).forEach(System.out::println);
StreamFromStreamOf.java
Creating streams. IntStream
IntStream.of(new int[] { 1, 2, 3 }).forEach(System.out::println);
IntStream.range(1, 3).forEach(System.out::println);
IntStream.rangeClosed(1, 3).forEach(System.out::println);
IntStreamFromIntStream.java
Creating streams. Infinite. Iterate
static <T> Stream<T> iterate(T seed, UnaryOperator<T> f)
IntStream.iterate(1, p -> p + 2).limit(10).forEach(System.out::
println);
StreamFromStreamInfiniteIterate.java
Creating streams. Infinite. Generate
static <T> Stream<T> generate(Supplier<T> s)
IntStream.generate(() -> (int) (System.nanoTime() % 100)).
limit(10)
.forEach(System.out::println);
StreamFromStreamInfiniteGenerate.java
Creating streams
● BufferedReader.lines
● Random.ints()
● File.list
● Pattern.splitAsStream
● JarFile.stream()
● ………..
StreamFromBufferedReader.java
StreamFromPatternSplitAsStream.java
Stream features
● No Storage
● Functional in nature
● Laziness-seeking
● Possibly unbounded
● Consumable
StreamFunctional.java
StreamLaziness.java
StreamConsumable.java
Stream Operators
● Intermediate (filter, map, limit, sorted ..)
● Terminal (forEach, reduce, findFirst, sum,
collect..)
● Short-circuiting (intermediate/terminal: limit ..
/findFirst..)
Stream Operators. Intermediate
map (mapToInt, flatMap, ..), filter, distinct, sorted, peek, limit, substream, parallel,
sequential, unordered ..
● Return new Stream
● Always lazy
● Stateless/stateful
filter,map/distinct,sorted
● Some short-circuiting (limit)
Stream Operators. Terminal
forEach, forEachOrdered, toArray, reduce, collect,
min, max, count, findFirst...
● Consumes pipeline/terminates
● Eager (except iterator,
spliterator)
● some short-circuiting (findFirst,
findAny)
Parallel Streams
● Collection.parallelStream()
BaseStream.parallel()
● same results as stream() apart
nondeterministic ops (findAny)
ParallelStreamFromListSimpleForEach.java
ParallelStreamLaziness.java
Parallel Streams. Non-interference
seq: terminal op starts -> do not update
source -> terminal op ends.
List<String> l = new ArrayList<String>(Arrays.asList("kaunas-jug", "meeting"));
Stream<String> sl = l.parallelStream();
l.add("#3");
String s = sl.collect(Collectors.joining(" "));
System.out.println(s);
NonInterference.java
Parallel Streams. Stateless behaviours
Best approach: avoid stateful behaviour
Set<Integer> seen = Collections.synchronizedSet(new HashSet<>());
List<Integer> numbers = Arrays.asList(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3);
List<Integer> result = numbers.parallelStream().map(e -> {return seen.add(e) ? 0 : e;
}).collect(Collectors.toList());
StatefulBehaviour.java
Parallel Streams. reduce. Associativity
(a op b) op c == a op (b op c)
a op b op c op d == (a op b) op (c op d)
IntStream stream = IntStream.rangeClosed(1, 4).
parallel();
OptionalInt rez = stream.reduce((x, y) -> x - y)
ReduceAssociativity.java
System.exit(0)
Thank You !

Weitere ähnliche Inhalte

Was ist angesagt?

Java 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven editionJava 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven edition
José Paumard
 
WebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPediaWebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPedia
Katrien Verbert
 

Was ist angesagt? (20)

Java 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven editionJava 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven edition
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
 
Free your lambdas
Free your lambdasFree your lambdas
Free your lambdas
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
 
WebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPediaWebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPedia
 
Functional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsFunctional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and Streams
 
Linking the world with Python and Semantics
Linking the world with Python and SemanticsLinking the world with Python and Semantics
Linking the world with Python and Semantics
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
 
Java SE 8 for Java EE developers
Java SE 8 for Java EE developersJava SE 8 for Java EE developers
Java SE 8 for Java EE developers
 
JFokus 50 new things with java 8
JFokus 50 new things with java 8JFokus 50 new things with java 8
JFokus 50 new things with java 8
 
Java SE 8 for Java EE developers
Java SE 8 for Java EE developersJava SE 8 for Java EE developers
Java SE 8 for Java EE developers
 
Rによる統計解析と可視化
Rによる統計解析と可視化Rによる統計解析と可視化
Rによる統計解析と可視化
 
Easy R
Easy REasy R
Easy R
 
Jena Programming
Jena ProgrammingJena Programming
Jena Programming
 
An Introduction to SPARQL
An Introduction to SPARQLAn Introduction to SPARQL
An Introduction to SPARQL
 
Querying Linked Data with SPARQL
Querying Linked Data with SPARQLQuerying Linked Data with SPARQL
Querying Linked Data with SPARQL
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In Java
 
Ramda, a functional JavaScript library
Ramda, a functional JavaScript libraryRamda, a functional JavaScript library
Ramda, a functional JavaScript library
 
Functional programming in java
Functional programming in javaFunctional programming in java
Functional programming in java
 

Ähnlich wie Java 8 Stream API (Valdas Zigas)

Ähnlich wie Java 8 Stream API (Valdas Zigas) (20)

RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]
 
«Практическое применение Akka Streams» — Алексей Романчук, 2ГИС
«Практическое применение Akka Streams» — Алексей Романчук, 2ГИС«Практическое применение Akka Streams» — Алексей Романчук, 2ГИС
«Практическое применение Akka Streams» — Алексей Романчук, 2ГИС
 
Практическое применения Akka Streams
Практическое применения Akka StreamsПрактическое применения Akka Streams
Практическое применения Akka Streams
 
Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
Flink internals web
Flink internals web Flink internals web
Flink internals web
 
Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
 
Java one 2010
Java one 2010Java one 2010
Java one 2010
 
Modern Java Development
Modern Java DevelopmentModern Java Development
Modern Java Development
 
Java8 training - class 3
Java8 training - class 3Java8 training - class 3
Java8 training - class 3
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemWprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
Apache Flink Overview at SF Spark and Friends
Apache Flink Overview at SF Spark and FriendsApache Flink Overview at SF Spark and Friends
Apache Flink Overview at SF Spark and Friends
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
Boost your craftsmanship with Java 8
Boost your craftsmanship with Java 8Boost your craftsmanship with Java 8
Boost your craftsmanship with Java 8
 
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
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 

Mehr von Kaunas Java User Group

Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)
Kaunas Java User Group
 
Kaunas JUG#1: Java History and Trends (Dainius Mezanskas)
Kaunas JUG#1: Java History and Trends (Dainius Mezanskas)Kaunas JUG#1: Java History and Trends (Dainius Mezanskas)
Kaunas JUG#1: Java History and Trends (Dainius Mezanskas)
Kaunas Java User Group
 

Mehr von Kaunas Java User Group (13)

Smart House Based on Raspberry PI + Java EE by Tadas Brasas
Smart House Based on Raspberry PI + Java EE by Tadas BrasasSmart House Based on Raspberry PI + Java EE by Tadas Brasas
Smart House Based on Raspberry PI + Java EE by Tadas Brasas
 
Presentation
PresentationPresentation
Presentation
 
Automated infrastructure
Automated infrastructureAutomated infrastructure
Automated infrastructure
 
Adf presentation
Adf presentationAdf presentation
Adf presentation
 
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)Bye Bye Cowboy Coder Days! (Legacy Code & TDD)
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)
 
Building with Gradle
Building with GradleBuilding with Gradle
Building with Gradle
 
Flyway
FlywayFlyway
Flyway
 
Eh cache in Kaunas JUG
Eh cache in Kaunas JUGEh cache in Kaunas JUG
Eh cache in Kaunas JUG
 
Apache Lucene Informacijos paieška
Apache Lucene Informacijos paieška Apache Lucene Informacijos paieška
Apache Lucene Informacijos paieška
 
Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)
 
Kaunas JUG#1: Intro (Valdas Zigas)
Kaunas JUG#1: Intro (Valdas Zigas)Kaunas JUG#1: Intro (Valdas Zigas)
Kaunas JUG#1: Intro (Valdas Zigas)
 
Kaunas JUG#1: Java History and Trends (Dainius Mezanskas)
Kaunas JUG#1: Java History and Trends (Dainius Mezanskas)Kaunas JUG#1: Java History and Trends (Dainius Mezanskas)
Kaunas JUG#1: Java History and Trends (Dainius Mezanskas)
 
Kaunas JUG#2: Devoxx 2013 (Saulius Tvarijonas)
Kaunas JUG#2: Devoxx 2013 (Saulius Tvarijonas)Kaunas JUG#2: Devoxx 2013 (Saulius Tvarijonas)
Kaunas JUG#2: Devoxx 2013 (Saulius Tvarijonas)
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

Java 8 Stream API (Valdas Zigas)

  • 1. Stream API Valdas Žigas · kaunas.jug@gmail.com · www.kaunas-jug.lt { λ } Java 8
  • 2. Valdas Žigas ● 13.6 x JAVA ● KTU Programų inžinerija ● SCJP 1.5, PL/SQL OCA ● Oracle University Delivery Instructor ● LKSoft, BPI, Infor, Affecto. PSE, uTrack
  • 4. Java 8 { λ }. Impression List<Long> idList = new ArrayList<>(); ... idList.stream().distinct().map(EmployeeStreamMain:: findById).filter(e -> e != null).filter(e -> e.getSalary() > 40000).findFirst().orElse(null);
  • 5. Java 8 { λ }. Impression 12 Years Without Lambdas ...
  • 6. java.util.stream.Stream<T> A sequence of elements supporting sequential and parallel bulk operations public interface Stream<T> extends BaseStream<T, Stream<T>> public interface BaseStream<T, S extends BaseStream<T, S>> extends AutoCloseable
  • 8. Simple example. forEach List<String> pronouns = Arrays.asList("i", "you", "he", "she", "it", "we", "you", "they"); pronouns.stream().forEach(p -> System.out.println(p)); StreamFromListSimpleForEach.java
  • 9. Simple example. forEach. Old school List<String> pronouns = Arrays.asList("i", "you", "he", "she", "it", "we", "you", "they"); pronouns.stream().forEach(new Consumer<String>() { public void accept(String p) { System.out.println(p); } }); StreamFromListSimpleForEachOldStyle.java
  • 10. Simple example. filter List<String> pronouns = Arrays.asList("i", "you", "he", "she", "it", "we", "you", "they"); pronouns.stream().distinct().filter(p -> p.length() == 3).forEach(p -> System.out.println(p)); StreamFromListSimpleFilter.java
  • 11. Simple example. filter. Old school pronouns.stream().distinct().filter(new Predicate<String>() { public boolean test(String p) { return p.length() == 3; } }).forEach(new Consumer<String>() { public void accept(String p) { System.out.println(p); }}); StreamFromListSimpleFilterOldStyle.java
  • 12. ● Collection.stream(), Collection.parallelStream() ● Arrays.stream(T[]) ● Stream.of(T...) ● IntStream.range(int, int) ● Stream.iterate(T, UnaryOperator<T>) Creating streams
  • 13. Creating streams. Arrays.stream Arrays.stream(new String[] { "This", "is", "Java8", "Stream" }) .forEach(System.out::println); Arrays.stream(new Integer[] { 1, 2, 3 }).forEach(System.out::println); Arrays.stream(new int[] { 1, 2, 3 }).forEach(System.out::println); StreamFromArraysStream.java
  • 14. Creating streams. Stream.of Stream.of("This", "is", "Java8", "Stream").forEach(System.out::println); Stream.of(new Integer[] { 1, 2, 3 }).forEach(System.out::println); Stream.of(new int[] { 1, 2, 3 }).forEach(System.out::println); StreamFromStreamOf.java
  • 15. Creating streams. IntStream IntStream.of(new int[] { 1, 2, 3 }).forEach(System.out::println); IntStream.range(1, 3).forEach(System.out::println); IntStream.rangeClosed(1, 3).forEach(System.out::println); IntStreamFromIntStream.java
  • 16. Creating streams. Infinite. Iterate static <T> Stream<T> iterate(T seed, UnaryOperator<T> f) IntStream.iterate(1, p -> p + 2).limit(10).forEach(System.out:: println); StreamFromStreamInfiniteIterate.java
  • 17. Creating streams. Infinite. Generate static <T> Stream<T> generate(Supplier<T> s) IntStream.generate(() -> (int) (System.nanoTime() % 100)). limit(10) .forEach(System.out::println); StreamFromStreamInfiniteGenerate.java
  • 18. Creating streams ● BufferedReader.lines ● Random.ints() ● File.list ● Pattern.splitAsStream ● JarFile.stream() ● ……….. StreamFromBufferedReader.java StreamFromPatternSplitAsStream.java
  • 19. Stream features ● No Storage ● Functional in nature ● Laziness-seeking ● Possibly unbounded ● Consumable StreamFunctional.java StreamLaziness.java StreamConsumable.java
  • 20. Stream Operators ● Intermediate (filter, map, limit, sorted ..) ● Terminal (forEach, reduce, findFirst, sum, collect..) ● Short-circuiting (intermediate/terminal: limit .. /findFirst..)
  • 21. Stream Operators. Intermediate map (mapToInt, flatMap, ..), filter, distinct, sorted, peek, limit, substream, parallel, sequential, unordered .. ● Return new Stream ● Always lazy ● Stateless/stateful filter,map/distinct,sorted ● Some short-circuiting (limit)
  • 22. Stream Operators. Terminal forEach, forEachOrdered, toArray, reduce, collect, min, max, count, findFirst... ● Consumes pipeline/terminates ● Eager (except iterator, spliterator) ● some short-circuiting (findFirst, findAny)
  • 23. Parallel Streams ● Collection.parallelStream() BaseStream.parallel() ● same results as stream() apart nondeterministic ops (findAny) ParallelStreamFromListSimpleForEach.java ParallelStreamLaziness.java
  • 24. Parallel Streams. Non-interference seq: terminal op starts -> do not update source -> terminal op ends. List<String> l = new ArrayList<String>(Arrays.asList("kaunas-jug", "meeting")); Stream<String> sl = l.parallelStream(); l.add("#3"); String s = sl.collect(Collectors.joining(" ")); System.out.println(s); NonInterference.java
  • 25. Parallel Streams. Stateless behaviours Best approach: avoid stateful behaviour Set<Integer> seen = Collections.synchronizedSet(new HashSet<>()); List<Integer> numbers = Arrays.asList(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3); List<Integer> result = numbers.parallelStream().map(e -> {return seen.add(e) ? 0 : e; }).collect(Collectors.toList()); StatefulBehaviour.java
  • 26. Parallel Streams. reduce. Associativity (a op b) op c == a op (b op c) a op b op c op d == (a op b) op (c op d) IntStream stream = IntStream.rangeClosed(1, 4). parallel(); OptionalInt rez = stream.reduce((x, y) -> x - y) ReduceAssociativity.java