SlideShare una empresa de Scribd logo
1 de 27
Descargar para leer sin conexión
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 !

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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 a 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» — Алексей Романчук, 2ГИС
«Практическое применение Akka Streams» — Алексей Романчук, 2ГИС«Практическое применение Akka Streams» — Алексей Романчук, 2ГИС
«Практическое применение Akka Streams» — Алексей Романчук, 2ГИС2ГИС Технологии
 
Практическое применения Akka Streams
Практическое применения Akka StreamsПрактическое применения Akka Streams
Практическое применения Akka StreamsAlexey Romanchuk
 
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 a 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()
 

Más de Kaunas Java User Group

Más de 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)
 

Último

Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 

Último (20)

Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 

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