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!
Ad

More Related Content

What's hot (20)

Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
Tobias Coetzee
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
Sanjoy Kumar Roy
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
Manvendra Singh
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
Drishti Bhalla
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
Jeevesh Pandey
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
NewCircle Training
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
Jeevesh Pandey
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
David Gómez García
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
NexThoughts Technologies
 
LINQ in C#
LINQ in C#LINQ in C#
LINQ in C#
Basant Medhat
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
Purbarun Chakrabarti
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
Manav Prasad
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
Rohit Verma
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
Erhan Bagdemir
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
icarter09
 
Java Collections
Java  Collections Java  Collections
Java Collections
Kongu Engineering College, Perundurai, Erode
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
Sergii Stets
 

Similar to Introduction to java 8 stream api (20)

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

Recently uploaded (20)

Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Asthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdfAsthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdf
VanessaRaudez
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.
gregtap1
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Buckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug LogsBuckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug Logs
Lynda Kane
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
 
"PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System""PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System"
Jainul Musani
 
Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical DebtBuckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Lynda Kane
 
Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from AnywhereAutomation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Lynda Kane
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Datastucture-Unit 4-Linked List Presentation.pptx
Datastucture-Unit 4-Linked List Presentation.pptxDatastucture-Unit 4-Linked List Presentation.pptx
Datastucture-Unit 4-Linked List Presentation.pptx
kaleeswaric3
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Image processinglab image processing image processing
Image processinglab image processing  image processingImage processinglab image processing  image processing
Image processinglab image processing image processing
RaghadHany
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Asthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdfAsthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdf
VanessaRaudez
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.
gregtap1
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Buckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug LogsBuckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug Logs
Lynda Kane
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
 
"PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System""PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System"
Jainul Musani
 
Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical DebtBuckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Lynda Kane
 
Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from AnywhereAutomation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Lynda Kane
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Datastucture-Unit 4-Linked List Presentation.pptx
Datastucture-Unit 4-Linked List Presentation.pptxDatastucture-Unit 4-Linked List Presentation.pptx
Datastucture-Unit 4-Linked List Presentation.pptx
kaleeswaric3
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Image processinglab image processing image processing
Image processinglab image processing  image processingImage processinglab image processing  image processing
Image processinglab image processing image processing
RaghadHany
 
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!