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

PDF
Java 8 Stream API and RxJava Comparison
PDF
Free your lambdas
PDF
Java 8 Streams and Rx Java Comparison
PDF
Going reactive in java
PDF
JDK8 : parallel programming made (too ?) easy
PDF
Collectors in the Wild
PDF
Linked to ArrayList: the full story
PDF
Autumn collection JavaOne 2014
Java 8 Stream API and RxJava Comparison
Free your lambdas
Java 8 Streams and Rx Java Comparison
Going reactive in java
JDK8 : parallel programming made (too ?) easy
Collectors in the Wild
Linked to ArrayList: the full story
Autumn collection JavaOne 2014

What's hot (20)

PDF
Java 8 Streams & Collectors : the Leuven edition
PDF
Java 8, Streams & Collectors, patterns, performances and parallelization
PDF
Free your lambdas
PDF
The Sincerest Form of Flattery
PDF
WebTech Tutorial Querying DBPedia
PDF
Functional Programming in Java 8 - Lambdas and Streams
PDF
Linking the world with Python and Semantics
PPTX
The Sincerest Form of Flattery
PDF
Asynchronous API in Java8, how to use CompletableFuture
PDF
Java SE 8 for Java EE developers
PPTX
JFokus 50 new things with java 8
PDF
Java SE 8 for Java EE developers
PDF
Rによる統計解析と可視化
PPT
Easy R
PPTX
Jena Programming
PDF
An Introduction to SPARQL
PDF
Querying Linked Data with SPARQL
PPT
Functional Programming In Java
PDF
Ramda, a functional JavaScript library
PDF
Functional programming in java
Java 8 Streams & Collectors : the Leuven edition
Java 8, Streams & Collectors, patterns, performances and parallelization
Free your lambdas
The Sincerest Form of Flattery
WebTech Tutorial Querying DBPedia
Functional Programming in Java 8 - Lambdas and Streams
Linking the world with Python and Semantics
The Sincerest Form of Flattery
Asynchronous API in Java8, how to use CompletableFuture
Java SE 8 for Java EE developers
JFokus 50 new things with java 8
Java SE 8 for Java EE developers
Rによる統計解析と可視化
Easy R
Jena Programming
An Introduction to SPARQL
Querying Linked Data with SPARQL
Functional Programming In Java
Ramda, a functional JavaScript library
Functional programming in java
Ad

Similar to Java 8 Stream API (Valdas Zigas) (20)

PDF
Java Streams Interview short reminder with examples
PPTX
Java Advanced Topic - Streams Presentations
PPT
Java 8 Streams
PDF
Charles Sharp: Java 8 Streams
PPTX
Introduction to java 8 stream api
PDF
Java 8 Streams - in Depth
PPTX
JDK8 Streams
PPTX
Java 8 streams
PPTX
Java 8 streams
PDF
Harnessing the Power of Java 8 Streams
PPTX
A Brief Conceptual Introduction to Functional Java 8 and its API
PPTX
Java 8 Lambda and Streams
PDF
JDK8 Functional API
PDF
Streams in Java 8
PDF
RxJava applied [JavaDay Kyiv 2016]
PDF
Functional programming with streams
PPTX
Java se 8 streams pt1
PDF
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
PDF
Lambda.pdf
PDF
Java Lambda internals with invoke dynamic
Java Streams Interview short reminder with examples
Java Advanced Topic - Streams Presentations
Java 8 Streams
Charles Sharp: Java 8 Streams
Introduction to java 8 stream api
Java 8 Streams - in Depth
JDK8 Streams
Java 8 streams
Java 8 streams
Harnessing the Power of Java 8 Streams
A Brief Conceptual Introduction to Functional Java 8 and its API
Java 8 Lambda and Streams
JDK8 Functional API
Streams in Java 8
RxJava applied [JavaDay Kyiv 2016]
Functional programming with streams
Java se 8 streams pt1
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
Lambda.pdf
Java Lambda internals with invoke dynamic
Ad

More from Kaunas Java User Group (13)

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

Recently uploaded (20)

PDF
Machine learning based COVID-19 study performance prediction
PPT
Teaching material agriculture food technology
PPTX
Big Data Technologies - Introduction.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
A Presentation on Artificial Intelligence
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
1. Introduction to Computer Programming.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Approach and Philosophy of On baking technology
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
Machine Learning_overview_presentation.pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
Machine learning based COVID-19 study performance prediction
Teaching material agriculture food technology
Big Data Technologies - Introduction.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
A Presentation on Artificial Intelligence
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
1. Introduction to Computer Programming.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Digital-Transformation-Roadmap-for-Companies.pptx
Network Security Unit 5.pdf for BCA BBA.
Diabetes mellitus diagnosis method based random forest with bat algorithm
Assigned Numbers - 2025 - Bluetooth® Document
Approach and Philosophy of On baking technology
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Empathic Computing: Creating Shared Understanding
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Machine Learning_overview_presentation.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”

Java 8 Stream API (Valdas Zigas)

  • 1. Stream API Valdas Žigas · [email protected] · 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