SlideShare a Scribd company logo
Introduction to
Java 8 Stream
API
Sidlyarevich Vladislav
Contacts/samples
● https://github.com/kuksenko/jdk8-lambda-samples
● https://github.com/vlsidlyarevich/Stream-API-Examples
● https://www.youtube.com/watch?v=O8oN4KSZEXE
● https://www.youtube.com/watch?v=i0Jr2l3jrDA
Java 8 language features
● Lambdas and Functional Interfaces
● Interface’s Default and Static Methods
● Method References
● Repeating annotations
Java 8 language features
● Date/Time API (JSR 310)
● Nashorn JavaScript engine
● Base64
● Parallel Arrays
● Concurrency
Java 8 language features
STREAM API!
Set<Person> freshBlood = new HashSet<>();
for (Person person : team) {
if (person.age <= 25) {
freshBlood.add(person);
}
}
List<Person> sortedFreshBlood = new ArrayList<>(freshBlood);
Collections.sort(sortedFreshBlood, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return Integer.compare(o1.age, o2.age);
}
});
for (Person person : sortedFreshBlood) {
System.out.println(person.name);
}
team.stream()
.filter(person -> person.age <= 25)
.collect(Collectors.toSet())
.stream()
.sorted(comparing(person -> person.age))
.forEach(person -> System.out.println(person.name));
source op op op
terminate
Profit
sources: collections, iterators, api’s
operations: filter, map, reduce, etc
sinks: collections, locals
What is Stream?
Multiplicity of values
Lazy
Single use
Not mutate the source
Ordered/Unordered
Parallel/Sequential
IntStream, DoubleStream, LongStream
What is Stream?
Sequence of elements − A stream provides a set of elements of specific type in a sequential
manner. A stream gets/computes elements on demand. It never stores the elements.
Source − Stream takes Collections, Arrays, or I/O resources as input source.
Aggregate operations − Stream supports aggregate operations like filter, map, limit, reduce,
find, match, and so on.
Pipelining − Most of the stream operations return stream itself so that their result can be
pipelined. These operations are called intermediate operations and their function is to take
input, process them, and return output to the target. collect() method is a terminal operation
which is normally present at the end of the pipelining operation to mark the end of the stream.
Automatic iterations − Stream operations do the iterations internally over the source elements
provided, in contrast to Collections where explicit iteration is required.
Stream pipeline
sources: team, stream operations: filter, sorted, forEach
sinks: collect
team.stream()
.filter(person -> person.age <= 25)
.collect(Collectors.toSet())
.stream()
.sorted(comparing(person -> person.age))
.forEach(person -> System.out.println(person.name));
Sources
Collections
Popular API’s (For example Regex)
String sentence = "Java 8 Stream tutorial";
Stream<String> regExpStream
= Pattern.compile("w").splitAsStream(sentence);
Sources
Infinite
Stream iterateStream = Stream.iterate(0, n -> n + 1).limit(2);
Function
Stream generatedStream = Stream.generate(Math::random).limit(5L);
List<String> arrList = new ArrayList<>();
Stream<String> arrListStream = arrList.stream(); //sized, ordered
List<String> linkedList = new LinkedList<>();
Stream<String> linkedListStream = linkedList.stream(); //sized, ordered
Set<String> hashSet = new HashSet<>();
Stream<String> hashSetStream = hashSet.stream(); //sized, distinct
Set<String> linkedHashSet = new LinkedHashSet<>();
Stream<String> linkedHashSetStream = linkedHashSet.stream(); //sized, distinct, ordered
Set<String> treeSet = new TreeSet<>();
Stream<String> treeSetStream = treeSet.stream(); //sized, distinct, sorted, ordered
source op op op
terminate
ProfitIntermediate
● Stream<S> s.distinct();
● Stream<S> s.filter(Predicate <S>);
● Stream<T> s.map(Function<S, T>);
● Stream<T> s.flatMap(Function<S, Stream<T>>);
● Stream<S> s.peek(Consumer<S>)
● Stream<S> s.sorted()
● Stream<S> s.limit(long);
● Stream<S> s.skip(long);
● Stream<S> s.distinct();
● Stream<S> s.filter(Predicate <S>);
● Stream<T> s.map(Function<S, T>);
● Stream<T> s.map(Function<S, Stream<T>>);
● Stream<S> s.peek(Consumer<S>)
● Stream<S> s.sorted()
● Stream<S> s.limit(long);
● Stream<S> s.skip(long);
● Stream<S> s.unordered();
● Stream<S> s.parallel();
● Stream<S> s.sequential();
Terminal operations = Profit
Terminal operations
iteration: forEach, iterator
search: findFirst, findAny
check: allMatch, anyMatch, noneMatch
aggregation: reduction, collectors
Short-circuiting
All find*
All match*
limit
int number = Stream.iterate(1, n -> n * 2)
.filter(n -> n % 1024 == 0)
.findFirst().get();
Examples
List<Transaction> groceryTransactions = new Arraylist<>();
for(Transaction t: transactions) {
if(t.getType() == Transaction.GROCERY) {
groceryTransactions.add(t);
}
}
Collections.sort(groceryTransactions, new Comparator() {
public int compare(Transaction t1, Transaction t2) {
return t2.getValue().compareTo(t1.getValue());
}
});
List<Integer> transactionIds = new ArrayList<>();
for(Transaction t: groceryTransactions) {
transactionsIds.add(t.getId());
}
Examples
List<Transaction> groceryTransactions = new Arraylist<>();
transactions.Stream()
.filter(t.getType() == Transaction.GROCERY)
Examples
List<Transaction> groceryTransactions = new Arraylist<>();
transactions.Stream()
.filter(t.getType() == Transaction.GROCERY)
.sorted(comparing(t -> t.getValue)
Examples
List<Transaction> groceryTransactions = new Arraylist<>();
transactions.Stream()
.filter(t.getType() == Transaction.GROCERY)
.sorted(comparing(t -> t.getValue).reversed)
Examples
List<Transaction> groceryTransactions = new Arraylist<>();
transactions.Stream()
.filter(t.getType() == Transaction.GROCERY)
.sorted(comparing(t -> t.getValue).reversed)
.map(transaction -> transaction.getId())
Examples
List<Transaction> groceryTransactions = new Arraylist<>();
transactions.Stream()
.filter(t.getType() == Transaction.GROCERY)
.sorted(comparing(t -> t.getValue).reversed)
.map(transaction -> transaction.getId())
.collect(Collectors.toList())
Examples
List<Transaction> groceryTransactions = new Arraylist<>();
transactions.Stream()
.filter(t.getType() == Transaction.GROCERY)
.sorted(comparing(Transaction::getValue).reversed)
.map(Transaction::getId())
.collect(Collectors.toList())
Thanks for your attention!

More Related Content

What's hot (20)

PPTX
Spring boot
sdeeg
 
PDF
Object oriented approach in python programming
Srinivas Narasegouda
 
PPTX
Spring boot Introduction
Jeevesh Pandey
 
PPTX
Java 11 to 17 : What's new !?
Jérôme Tamborini
 
PDF
Object-oriented Programming-with C#
Doncho Minkov
 
PPTX
Unit Testing with Python
MicroPyramid .
 
PPTX
Clean Code I - Best Practices
Theo Jungeblut
 
PDF
Spring Framework - Core
Dzmitry Naskou
 
PDF
Collections In Java
Binoj T E
 
PPT
Java 8 Streams
Manvendra Singh
 
PPT
Introduction To C#
SAMIR BHOGAYTA
 
PDF
Api presentation
Tiago Cardoso
 
PPTX
Java Spring
AathikaJava
 
PDF
Spring boot jpa
Hamid Ghorbani
 
PPTX
Java 8 Lambda and Streams
Venkata Naga Ravi
 
PPTX
Introduction to laravel framework
Ahmad Fatoni
 
PPTX
How Hashmap works internally in java
Ramakrishna Joshi
 
PPTX
Sqlite
Raghu nath
 
PPTX
Soap vs rest
Antonio Severien
 
Spring boot
sdeeg
 
Object oriented approach in python programming
Srinivas Narasegouda
 
Spring boot Introduction
Jeevesh Pandey
 
Java 11 to 17 : What's new !?
Jérôme Tamborini
 
Object-oriented Programming-with C#
Doncho Minkov
 
Unit Testing with Python
MicroPyramid .
 
Clean Code I - Best Practices
Theo Jungeblut
 
Spring Framework - Core
Dzmitry Naskou
 
Collections In Java
Binoj T E
 
Java 8 Streams
Manvendra Singh
 
Introduction To C#
SAMIR BHOGAYTA
 
Api presentation
Tiago Cardoso
 
Java Spring
AathikaJava
 
Spring boot jpa
Hamid Ghorbani
 
Java 8 Lambda and Streams
Venkata Naga Ravi
 
Introduction to laravel framework
Ahmad Fatoni
 
How Hashmap works internally in java
Ramakrishna Joshi
 
Sqlite
Raghu nath
 
Soap vs rest
Antonio Severien
 

Similar to Introduction to java 8 stream api (20)

PPTX
New Features in JDK 8
Martin Toshev
 
PPTX
Hot Streaming Java
nick_maiorano
 
PPTX
What is new in Java 8
Sandeep Kr. Singh
 
PPTX
Tk2323 lecture 9 api json
MengChun Lam
 
PDF
Functional programming in Java 8 - workshop at flatMap Oslo 2014
Fredrik Vraalsen
 
PPTX
New features in jdk8 iti
Ahmed mar3y
 
PDF
Java 8 - Return of the Java
Fredrik Vraalsen
 
PDF
Xlab #1: Advantages of functional programming in Java 8
XSolve
 
PPTX
Java 8 presentation
Van Huong
 
PPTX
FUNctional Programming in Java 8
Richard Walker
 
PDF
Ruby on Rails Oracle adaptera izstrāde
Raimonds Simanovskis
 
PDF
Java 8 new features or the ones you might actually use
Sharon Rozinsky
 
PDF
Java 8 Stream API (Valdas Zigas)
Kaunas Java User Group
 
PPTX
Belfast JUG 23-10-2013
eamonnlong
 
PDF
Node.js Stream API
The Software House
 
PDF
Specification-Driven Development of REST APIs by Alexander Zinchuk
OdessaJS Conf
 
PPTX
Java 8 Intro - Core Features
GlobalLogic Ukraine
 
PDF
Intro to Spark and Spark SQL
jeykottalam
 
PPT
Developing RESTful WebServices using Jersey
b_kathir
 
PDF
Eclipse Collections, Java Streams & Vavr - What's in them for Functional Pro...
Naresha K
 
New Features in JDK 8
Martin Toshev
 
Hot Streaming Java
nick_maiorano
 
What is new in Java 8
Sandeep Kr. Singh
 
Tk2323 lecture 9 api json
MengChun Lam
 
Functional programming in Java 8 - workshop at flatMap Oslo 2014
Fredrik Vraalsen
 
New features in jdk8 iti
Ahmed mar3y
 
Java 8 - Return of the Java
Fredrik Vraalsen
 
Xlab #1: Advantages of functional programming in Java 8
XSolve
 
Java 8 presentation
Van Huong
 
FUNctional Programming in Java 8
Richard Walker
 
Ruby on Rails Oracle adaptera izstrāde
Raimonds Simanovskis
 
Java 8 new features or the ones you might actually use
Sharon Rozinsky
 
Java 8 Stream API (Valdas Zigas)
Kaunas Java User Group
 
Belfast JUG 23-10-2013
eamonnlong
 
Node.js Stream API
The Software House
 
Specification-Driven Development of REST APIs by Alexander Zinchuk
OdessaJS Conf
 
Java 8 Intro - Core Features
GlobalLogic Ukraine
 
Intro to Spark and Spark SQL
jeykottalam
 
Developing RESTful WebServices using Jersey
b_kathir
 
Eclipse Collections, Java Streams & Vavr - What's in them for Functional Pro...
Naresha K
 
Ad

Recently uploaded (20)

PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
Understanding The True Cost of DynamoDB Webinar
ScyllaDB
 
PPTX
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
Governing Geospatial Data at Scale: Optimizing ArcGIS Online with FME in Envi...
Safe Software
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PDF
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
PDF
Introducing and Operating FME Flow for Kubernetes in a Large Enterprise: Expe...
Safe Software
 
PPTX
Securing Model Context Protocol with Keycloak: AuthN/AuthZ for MCP Servers
Hitachi, Ltd. OSS Solution Center.
 
PPTX
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
PDF
How to Comply With Saudi Arabia’s National Cybersecurity Regulations.pdf
Bluechip Advanced Technologies
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
PDF
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
PDF
Next Generation AI: Anticipatory Intelligence, Forecasting Inflection Points ...
dleka294658677
 
PDF
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Understanding The True Cost of DynamoDB Webinar
ScyllaDB
 
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Governing Geospatial Data at Scale: Optimizing ArcGIS Online with FME in Envi...
Safe Software
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
Introducing and Operating FME Flow for Kubernetes in a Large Enterprise: Expe...
Safe Software
 
Securing Model Context Protocol with Keycloak: AuthN/AuthZ for MCP Servers
Hitachi, Ltd. OSS Solution Center.
 
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
How to Comply With Saudi Arabia’s National Cybersecurity Regulations.pdf
Bluechip Advanced Technologies
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
Next Generation AI: Anticipatory Intelligence, Forecasting Inflection Points ...
dleka294658677
 
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
Ad

Introduction to java 8 stream api

  • 1. Introduction to Java 8 Stream API Sidlyarevich Vladislav
  • 2. Contacts/samples ● https://github.com/kuksenko/jdk8-lambda-samples ● https://github.com/vlsidlyarevich/Stream-API-Examples ● https://www.youtube.com/watch?v=O8oN4KSZEXE ● https://www.youtube.com/watch?v=i0Jr2l3jrDA
  • 3. Java 8 language features ● Lambdas and Functional Interfaces ● Interface’s Default and Static Methods ● Method References ● Repeating annotations
  • 4. Java 8 language features ● Date/Time API (JSR 310) ● Nashorn JavaScript engine ● Base64 ● Parallel Arrays ● Concurrency
  • 5. Java 8 language features STREAM API!
  • 6. Set<Person> freshBlood = new HashSet<>(); for (Person person : team) { if (person.age <= 25) { freshBlood.add(person); } } List<Person> sortedFreshBlood = new ArrayList<>(freshBlood); Collections.sort(sortedFreshBlood, new Comparator<Person>() { @Override public int compare(Person o1, Person o2) { return Integer.compare(o1.age, o2.age); } }); for (Person person : sortedFreshBlood) { System.out.println(person.name); }
  • 7. team.stream() .filter(person -> person.age <= 25) .collect(Collectors.toSet()) .stream() .sorted(comparing(person -> person.age)) .forEach(person -> System.out.println(person.name));
  • 8. source op op op terminate Profit
  • 9. sources: collections, iterators, api’s operations: filter, map, reduce, etc sinks: collections, locals
  • 10. What is Stream? Multiplicity of values Lazy Single use Not mutate the source Ordered/Unordered Parallel/Sequential IntStream, DoubleStream, LongStream
  • 11. What is Stream? Sequence of elements − A stream provides a set of elements of specific type in a sequential manner. A stream gets/computes elements on demand. It never stores the elements. Source − Stream takes Collections, Arrays, or I/O resources as input source. Aggregate operations − Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on. Pipelining − Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream. Automatic iterations − Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required.
  • 12. Stream pipeline sources: team, stream operations: filter, sorted, forEach sinks: collect team.stream() .filter(person -> person.age <= 25) .collect(Collectors.toSet()) .stream() .sorted(comparing(person -> person.age)) .forEach(person -> System.out.println(person.name));
  • 13. Sources Collections Popular API’s (For example Regex) String sentence = "Java 8 Stream tutorial"; Stream<String> regExpStream = Pattern.compile("w").splitAsStream(sentence);
  • 14. Sources Infinite Stream iterateStream = Stream.iterate(0, n -> n + 1).limit(2); Function Stream generatedStream = Stream.generate(Math::random).limit(5L);
  • 15. List<String> arrList = new ArrayList<>(); Stream<String> arrListStream = arrList.stream(); //sized, ordered List<String> linkedList = new LinkedList<>(); Stream<String> linkedListStream = linkedList.stream(); //sized, ordered Set<String> hashSet = new HashSet<>(); Stream<String> hashSetStream = hashSet.stream(); //sized, distinct Set<String> linkedHashSet = new LinkedHashSet<>(); Stream<String> linkedHashSetStream = linkedHashSet.stream(); //sized, distinct, ordered Set<String> treeSet = new TreeSet<>(); Stream<String> treeSetStream = treeSet.stream(); //sized, distinct, sorted, ordered
  • 16. source op op op terminate ProfitIntermediate
  • 17. ● Stream<S> s.distinct(); ● Stream<S> s.filter(Predicate <S>); ● Stream<T> s.map(Function<S, T>); ● Stream<T> s.flatMap(Function<S, Stream<T>>); ● Stream<S> s.peek(Consumer<S>) ● Stream<S> s.sorted() ● Stream<S> s.limit(long); ● Stream<S> s.skip(long);
  • 18. ● Stream<S> s.distinct(); ● Stream<S> s.filter(Predicate <S>); ● Stream<T> s.map(Function<S, T>); ● Stream<T> s.map(Function<S, Stream<T>>); ● Stream<S> s.peek(Consumer<S>) ● Stream<S> s.sorted() ● Stream<S> s.limit(long); ● Stream<S> s.skip(long); ● Stream<S> s.unordered(); ● Stream<S> s.parallel(); ● Stream<S> s.sequential();
  • 20. Terminal operations iteration: forEach, iterator search: findFirst, findAny check: allMatch, anyMatch, noneMatch aggregation: reduction, collectors
  • 21. Short-circuiting All find* All match* limit int number = Stream.iterate(1, n -> n * 2) .filter(n -> n % 1024 == 0) .findFirst().get();
  • 22. Examples List<Transaction> groceryTransactions = new Arraylist<>(); for(Transaction t: transactions) { if(t.getType() == Transaction.GROCERY) { groceryTransactions.add(t); } } Collections.sort(groceryTransactions, new Comparator() { public int compare(Transaction t1, Transaction t2) { return t2.getValue().compareTo(t1.getValue()); } }); List<Integer> transactionIds = new ArrayList<>(); for(Transaction t: groceryTransactions) { transactionsIds.add(t.getId()); }
  • 23. Examples List<Transaction> groceryTransactions = new Arraylist<>(); transactions.Stream() .filter(t.getType() == Transaction.GROCERY)
  • 24. Examples List<Transaction> groceryTransactions = new Arraylist<>(); transactions.Stream() .filter(t.getType() == Transaction.GROCERY) .sorted(comparing(t -> t.getValue)
  • 25. Examples List<Transaction> groceryTransactions = new Arraylist<>(); transactions.Stream() .filter(t.getType() == Transaction.GROCERY) .sorted(comparing(t -> t.getValue).reversed)
  • 26. Examples List<Transaction> groceryTransactions = new Arraylist<>(); transactions.Stream() .filter(t.getType() == Transaction.GROCERY) .sorted(comparing(t -> t.getValue).reversed) .map(transaction -> transaction.getId())
  • 27. Examples List<Transaction> groceryTransactions = new Arraylist<>(); transactions.Stream() .filter(t.getType() == Transaction.GROCERY) .sorted(comparing(t -> t.getValue).reversed) .map(transaction -> transaction.getId()) .collect(Collectors.toList())
  • 28. Examples List<Transaction> groceryTransactions = new Arraylist<>(); transactions.Stream() .filter(t.getType() == Transaction.GROCERY) .sorted(comparing(Transaction::getValue).reversed) .map(Transaction::getId()) .collect(Collectors.toList())
  • 29. Thanks for your attention!