SlideShare a Scribd company logo
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 !

More Related Content

What's hot

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 editionJosé Paumard
 
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 parallelizationJosé Paumard
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of FlatteryJosé Paumard
 
WebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPediaWebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPediaKatrien Verbert
 
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 StreamsCodeOps Technologies LLP
 
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 SemanticsTatiana Al-Chueyr
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of FlatteryJosé Paumard
 
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 CompletableFutureJosé Paumard
 
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 developersJosé Paumard
 
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 8José Paumard
 
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 developersJosé Paumard
 
Rによる統計解析と可視化
Rによる統計解析と可視化Rによる統計解析と可視化
Rによる統計解析と可視化弘毅 露崎
 
An Introduction to SPARQL
An Introduction to SPARQLAn Introduction to SPARQL
An Introduction to SPARQLOlaf Hartig
 
Querying Linked Data with SPARQL
Querying Linked Data with SPARQLQuerying Linked Data with SPARQL
Querying Linked Data with SPARQLOlaf Hartig
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In JavaAndrei Solntsev
 
Ramda, a functional JavaScript library
Ramda, a functional JavaScript libraryRamda, a functional JavaScript library
Ramda, a functional JavaScript libraryDerek Willian Stavis
 

What's hot (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
 

Similar to Java 8 Stream API (Valdas Zigas)

RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]Igor Lozynskyi
 
Практическое применения Akka Streams
Практическое применения Akka StreamsПрактическое применения Akka Streams
Практическое применения Akka StreamsAlexey Romanchuk
 
«Практическое применение Akka Streams» — Алексей Романчук, 2ГИС
«Практическое применение Akka Streams» — Алексей Романчук, 2ГИС«Практическое применение Akka Streams» — Алексей Романчук, 2ГИС
«Практическое применение Akka Streams» — Алексей Романчук, 2ГИС2ГИС Технологии
 
Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8Madina Kamzina
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
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 CodeIan Robertson
 
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 IndicThreads
 
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 APIJörn Guy Süß JGS
 
Java one 2010
Java one 2010Java one 2010
Java one 2010scdn
 
Java8 training - class 3
Java8 training - class 3Java8 training - class 3
Java8 training - class 3Marut Singh
 
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 EcosystemSages
 
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 FriendsStephan Ewen
 
Boost your craftsmanship with Java 8
Boost your craftsmanship with Java 8Boost your craftsmanship with Java 8
Boost your craftsmanship with Java 8João Nunes
 
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
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
 

Similar to 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
Практическое применения Akka StreamsПрактическое применения Akka Streams
Практическое применения Akka Streams
 
«Практическое применение Akka Streams» — Алексей Романчук, 2ГИС
«Практическое применение Akka Streams» — Алексей Романчук, 2ГИС«Практическое применение Akka Streams» — Алексей Романчук, 2ГИС
«Практическое применение Akka Streams» — Алексей Романчук, 2ГИС
 
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()
 

More from Kaunas Java User Group

More from 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)
 

Recently uploaded

In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsExpeed Software
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Julian Hyde
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCzechDreamin
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationZilliz
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...Product School
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...Product School
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Product School
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Product School
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaCzechDreamin
 
The architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdfThe architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdfalexjohnson7307
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...CzechDreamin
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomCzechDreamin
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaRTTS
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxDavid Michel
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyJohn Staveley
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekCzechDreamin
 

Recently uploaded (20)

In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT Professionals
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG Evaluation
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
The architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdfThe architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdf
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 

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