SlideShare ist ein Scribd-Unternehmen logo
1 von 47
Downloaden Sie, um offline zu lesen
Harnessing the power of
Java 8 Streams
Praveer Gupta
Default Methods
Lambda Expressions
Streams
Date-Time API
CompletableFuture
Optional
helps to make a strategic decision about what
programming language should be adopted
when starting to build a new software system
Java 8 released on
Mar 18, 2014
–Robert C. Martin
“There are two parts to learning
craftsmanship: knowledge and work.
You must gain the knowledge of
principles, patterns, practices, and
heuristics that a craftsman knows,
and
you must also grind that knowledge
into your fingers, eyes, and gut by
working hard and
practicing..”
Stream
Intermediate Operators
Terminal Operators
Harnessing the power Java 8 Streams
Programming Paradigm Concepts
Stream
Collectorscollectreduce
Intermediate Operators
Terminal Operators
computation creation Primitive Streams
stateless/stateful
Lazy &
Short-Circuited
Harnessing the power Java 8 Streams
Declarative
Programming
Internal
Iteration
chained categories
Programming Paradigm Concepts
Harnessing the power Java 8 Streams
Declarative
Programming
Internal
Iteration
Programming Paradigm Concepts
Declarative
SELECT NAME FROM PERSON WHERE AGE > 18;
List<String> adults = group.stream()

.filter(p -> p.age() > 18)
.map(Person::name)

.collect(toList());
You declare what the program has to do
and the library takes care of how to do it
Declarative
Focuses on
What
List<String> adults = new ArrayList<>();

for (Person person: group) 

if (person.age() > 18)

adults.add(person.name());
Focuses on
How and
What
vs Imperative
List<String> adults = group.stream()

.filter(p -> p.age() > 18)
.map(Person::name)

.collect(toList());
Old way vs New way
final List<String> names = new ArrayList<>();

for (Person p : group)

if (p.age() > 18)
names.add(p.name());

return names;
return group.stream()

.filter(p -> p.age() > 18)

.map(Person::name)

.collect(toList());
List<String> namesOfAdultsInTheGroup(List<Person> group) {
}
External Iteration
Internal Iteration
new declarative way
old imperative way
List<String> namesOfAdultsInTheGroup(List<Person> group) {
}
Application of Streams
interface CustomerRepository {

List<Customer> findByCity(String cityName);

}
API Definition
Application of Streams
interface CustomerRepository {

Stream<Customer> findByCity(String cityName);

}
try (Stream<String> stream =
repository.findByCity(“Pune")) {

return stream.filter(…).count();

}
API Definition
Usage of the API
Consume items as they arrive
Efficient memory usage
Stream
computation creation
Harnessing the power Java 8 Streams
Declarative
Programming
Internal
Iteration
Programming Paradigm Concepts
Stream
a read-only sequence of elements
computational operations that will be performed
in aggregate
Collection
efficient management of elements
efficient access to elements
Stream Pipeline
Stream
Terminal
Operator
Operator1
Operator2
Operator3
Intermediate
Operators
(Zero or more)
Stream
Terminal
Operator
Operator1
Operator2
Operator3
Stream Pipeline
List<String> namesOfAdultsInTheGroup(List<Person> group) {

return







}
group.stream()
.filter(p -> p.age() > 18)
.map(Person::name)
.collect(Collectors.toList());
names
group
Stream<Person>
Archer
(22 years)
Barbara
(17 years)
Daisy
(25 years)
is person’s age > 18 ?
Stream<Person>
Stream<String>
map to name of person
collect into a list
group.stream()
.filter(p ->
p.age() > 18)
.map(Person::name)
.collect(
Collectors.toList());
Archer
(22 years)
Barbara
(17 years)
Daisy
(25 years)
Archer
(22 years)
Daisy
(25 years)
Archer Daisy
Archer Daisy
Creating Stream
From Collection
List<String> list = Arrays.asList("a", "b", "c");

Stream<String> stream = list.stream();
String[] array = {"a", "b", "c"};

Stream<String> stream = Arrays.stream(array);
Creating Stream
From an I/O Channel
try (Stream<Path> stream =
Files.list(Paths.get(“.”));) {
…
}
Stream interface extends AutoCloseable
Creating Stream
Using Generator Functions
Stream<Double> stream = Stream.generate(Math::random);
Stream<Integer> stream = Stream.iterate(0, n -> n + 3);
Both are unbounded
Parallel Stream
From Collection
List<String> list = Arrays.asList("a", "b", "c");

Stream<String> stream = list.parallelStream();
From another Stream
Stream<String> parallelStream = stream.parallel();
List<String> list = Arrays.asList("a", "b", "c");

Stream<String> stream = list.parallelStream();
Stream<String> parallelStream = stream.parallel();
Parallel Stream
How does it work?
Splitting Combining
Parallel
Processing
Parallel Stream
Performance Impact
Always measure performance before using parallel
Stream size predictability & Amount of data
Decomposability of source data structure
Computational Cost
Stream
Intermediate Operators
computation creation
stateless/stateful
Harnessing the power Java 8 Streams
Declarative
Programming
Internal
Iteration
chained categories
Programming Paradigm Concepts
Intermediate Operators
Stream
Terminal
Operator
Operator1
Operator2
Operator3
Intermediate
Operators
(Zero or more)
Intermediate Operators
Categories
Stream<Integer> stream = Stream.of(3, 2, 1);
Stream<Integer> filtered =
stream.filter(n -> n % 2 == 0);
Filtering
Type of stream remains the same
Stream<Integer> filtered =
stream.filter(n -> n % 2 == 0);
Intermediate Operators
Categories
Stream<Integer> stream = Stream.of(3, 2, 1);
Stream<String> mapped = stream.map(Object::toString);
Mapping
Type of stream gets altered (here Integer to String)
Stream<String> mapped = stream.map(Object::toString);
Intermediate Operators
Categories
Stream<Integer> stream = Stream.of(3, 2, 1);
Stream<Integer> sliced = stream.limit(1);
Slicing
Type of stream remains the same
Stream<Integer> sliced = stream.limit(1);
Stream.of(1, 2, 3, 4)

.peek(System.out::println)

.filter(n -> n % 2 == 0);
Intermediate Operators
Laziness
Stream.of(1, 2, 3, 4)

.peek(System.out::println)

.filter(n -> n % 2 == 0)

.collect(toList());
Stream.of(1, 2, 3, 4)

.peek(System.out::println)

.filter(n -> n % 2 == 0);
Terminal operator is required to start stream processing
Stream.of(1, 2, 3, 4)

.peek(System.out::println)

.filter(n -> n % 2 == 0)

.collect(toList());
Peek will not print
anything
Intermediate Operators
Short-Circuiting
Stream.of(1, 2, 3, 4)

.peek(System.out::println)

.filter(n -> n % 2 == 0)

.findFirst();
Stream will get short-circuited
after the first element is found
Peek will print
only 1 & 2
Stream.of(1, 2, 3, 4)

.peek(System.out::println)

.filter(n -> n % 2 == 0)

.findFirst();
Intermediate Operators
Stateless
vs Stateful
Stream.of(1, 2, 3, 4)

.peek(System.out::println)

.filter(n -> n % 2 == 0)

.findFirst();
Stream.of(1, 2, 3, 4)

.peek(System.out::println)

.sorted(Comparator.reverseOrder())

.filter(n -> n % 2 == 0)

.findFirst();
Will cause the
whole stream
to be
traversed
All operations
are done on
current value
in stream
Stream.of(1, 2, 3, 4)

.peek(System.out::println)

.sorted(Comparator.reverseOrder())

.filter(n -> n % 2 == 0)

.findFirst();
Stream
Collectorscollectreduce
Intermediate Operators
Terminal Operators
computation creation
stateless/stateful
Lazy &
Short-Circuited
Harnessing the power Java 8 Streams
Declarative
Programming
Internal
Iteration
chained categories
Programming Paradigm Concepts
Terminal Operators
Single Value Collection
Reduce Operation Collect Operation
Terminal Operators
reduce
<U> U reduce(U identity,

BiFunction<U, ? super T, U> accumulator,

BinaryOperator<U> combiner);
Stream.of(3, 2, 1).reduce(0, Integer::sum, Integer::sum);
Stream.of(3, 2, 1).reduce(0, Integer::sum);
Immutable Reduction Process
<U> U reduce(U identity,

BiFunction<U, ? super T, U> accumulator,

BinaryOperator<U> combiner);
<U> U reduce(U identity,

BiFunction<U, ? super T, U> accumulator,

BinaryOperator<U> combiner);
<U> U reduce(U identity,

BiFunction<U, ? super T, U> accumulator,

BinaryOperator<U> combiner);
Terminal Operators
reduce utility methods
Optional<Integer> max =
Stream.of(1, 2, 3)
.max(Comparator.naturalOrder());
boolean result = Stream.of(1, 2, 3)
.anyMatch(n -> n > 2);
Optional<Integer> max =
Stream.of(1, 2, 3)
.max(Comparator.naturalOrder());
boolean result = Stream.of(1, 2, 3)
.anyMatch(n -> n > 2);
Terminal Operators
collect
Mutable Reduction Process
Accumulates elements into a mutable result container
Stream.of("a", "b", "c").reduce("", String::concat);
String copying = Low Performance !!
Terminal Operators
collect
<R> R collect(Supplier<R> supplier,

BiConsumer<R, ? super T> accumulator,

BiConsumer<R, R> combiner);
StringBuilder builder = Stream.of("a", "b", "c").collect(

StringBuilder::new, 

StringBuilder::append, 

StringBuilder::append

);
StringBuilder is the mutable container here
Terminal Operators
Collectors class
String joinedString = Stream.of(“a", "b", “c")
.collect(Collectors.joining(", "));
IntSummaryStatistics statistics = group.stream()
.collect(Collectors.summarizingInt(Person::age));
IntSummaryStatistics{count=10, sum=280, min=26, average=28.000000, max=30}
Output: a, b, c
String joinedString = Stream.of(“a", "b", “c")
.collect(Collectors.joining(", "));
IntSummaryStatistics statistics = group.stream()
.collect(Collectors.summarizingInt(Person::age));
Terminal Operators
Downstream Collectors
Map<Integer, List<Person>> result = group.stream()
.collect(Collectors.groupingBy(Person::age,

Collectors.toList()));
Map<Integer, List<Person>> result = group.stream()
.collect(groupingBy(Person::age));
Divide into different age groups
Terminal Operators
Downstream Collectors
Map<Integer, Long> result = group.stream()
.collect(groupingBy(Person::age, counting()));
Map<Integer, List<String>> result = group.stream()
.collect(groupingBy(Person::age,

mapping(Person::name, toList())));
Count of people in each age group
Names on people in each age group
Stream
Collectorscollectreduce
Intermediate Operators
Terminal Operators
computation creation Primitive Streams
stateless/stateful
Lazy &
Short-Circuited
Harnessing the power Java 8 Streams
Declarative
Programming
Internal
Iteration
chained categories
Programming Paradigm Concepts
Primitive Streams
IntStream DoubleStreamLongStream
Avoid boxing and
unboxing costs
Numeric operations
are available
XXXFunction
XXXPredicateXXXSupplierXXXConsumer
XXXToXXXFunction
Primitive Functional Interfaces
Primitive Streams
Creating from factory methods
IntStream intStream = IntStream.range(1, 10);
DoubleStream doubleStream = DoubleStream.of(1.0, 2.0);
LongStream longStream =
LongStream.iterate(0L, n -> n + 4);
Generating a range of numbers
Stream of known set of numbers
Stream using iterative application of a function
Stream<Person> stream = group.stream();
Primitive Streams
Obtaining from Stream<T>
mapToXXX flatMapToXXX
IntStream intStream = stream.mapToInt(Person::age);
OptionalDouble averageAge = intStream.average();
Specialized methods on Primitive Streams
IntStream intStream = stream.mapToInt(Person::age);
Primitive Streams
Converting back to Stream<T>
Stream<Integer> boxed = IntStream.of(1, 2, 3).boxed();Stream<Integer> boxed = IntStream.of(1, 2, 3).boxed();
Stream
Collectorscollectreduce
Intermediate Operators
Terminal Operators
computation creation Primitive Streams
stateless/stateful
Lazy &
Short-Circuited
Harnessing the power Java 8 Streams
Declarative
Programming
Internal
Iteration
chained categories
Programming Paradigm Concepts
Questions?
http://praveer09.github.io
@praveerguptapraveer

Weitere ähnliche Inhalte

Was ist angesagt?

If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of LambdasEsther Lozano
 
Reactive programming with RxJava
Reactive programming with RxJavaReactive programming with RxJava
Reactive programming with RxJavaJobaer Chowdhury
 
Flink Batch Processing and Iterations
Flink Batch Processing and IterationsFlink Batch Processing and Iterations
Flink Batch Processing and IterationsSameer Wadkar
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...Mario Fusco
 
An Introduction to RxJava
An Introduction to RxJavaAn Introduction to RxJava
An Introduction to RxJavaSanjay Acharya
 
Apache Flink Training: DataSet API Basics
Apache Flink Training: DataSet API BasicsApache Flink Training: DataSet API Basics
Apache Flink Training: DataSet API BasicsFlink Forward
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer farooq
 
Spark schema for free with David Szakallas
Spark schema for free with David SzakallasSpark schema for free with David Szakallas
Spark schema for free with David SzakallasDatabricks
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
 
Functional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSFunctional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSOswald Campesato
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 

Was ist angesagt? (20)

If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
Rxjava meetup presentation
Rxjava meetup presentationRxjava meetup presentation
Rxjava meetup presentation
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Hot Streaming Java
Hot Streaming JavaHot Streaming Java
Hot Streaming Java
 
Reactive programming with RxJava
Reactive programming with RxJavaReactive programming with RxJava
Reactive programming with RxJava
 
Flink Batch Processing and Iterations
Flink Batch Processing and IterationsFlink Batch Processing and Iterations
Flink Batch Processing and Iterations
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...
 
An Introduction to RxJava
An Introduction to RxJavaAn Introduction to RxJava
An Introduction to RxJava
 
Apache Flink Training: DataSet API Basics
Apache Flink Training: DataSet API BasicsApache Flink Training: DataSet API Basics
Apache Flink Training: DataSet API Basics
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
Spark schema for free with David Szakallas
Spark schema for free with David SzakallasSpark schema for free with David Szakallas
Spark schema for free with David Szakallas
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
 
Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
 
CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
Functional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSFunctional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJS
 
Java Language fundamental
Java Language fundamentalJava Language fundamental
Java Language fundamental
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 

Ähnlich wie Harnessing the Power of Java 8 Streams

Functional Programming in Java - Code for Maintainability
Functional Programming in Java - Code for MaintainabilityFunctional Programming in Java - Code for Maintainability
Functional Programming in Java - Code for MaintainabilityMarcin Stepien
 
Hierarchical free monads and software design in fp
Hierarchical free monads and software design in fpHierarchical free monads and software design in fp
Hierarchical free monads and software design in fpAlexander Granin
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Harmeet Singh(Taara)
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]Igor Lozynskyi
 
Apache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapApache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapKostas Tzoumas
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8franciscoortin
 
Lessons Learnt With Lambdas and Streams in JDK 8
Lessons Learnt With Lambdas and Streams in JDK 8Lessons Learnt With Lambdas and Streams in JDK 8
Lessons Learnt With Lambdas and Streams in JDK 8Simon Ritter
 
A calculus of mobile Real-Time processes
A calculus of mobile Real-Time processesA calculus of mobile Real-Time processes
A calculus of mobile Real-Time processesPolytechnique Montréal
 
Reactive stream processing using Akka streams
Reactive stream processing using Akka streams Reactive stream processing using Akka streams
Reactive stream processing using Akka streams Johan Andrén
 
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 useSharon Rozinsky
 
Development of a Distributed Stream Processing System
Development of a Distributed Stream Processing SystemDevelopment of a Distributed Stream Processing System
Development of a Distributed Stream Processing SystemMaycon Viana Bordin
 
VCE Unit 01 (1).pptx
VCE Unit 01 (1).pptxVCE Unit 01 (1).pptx
VCE Unit 01 (1).pptxskilljiolms
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressionsLogan Chien
 
Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8Madina Kamzina
 

Ähnlich wie Harnessing the Power of Java 8 Streams (20)

Functional Programming in Java - Code for Maintainability
Functional Programming in Java - Code for MaintainabilityFunctional Programming in Java - Code for Maintainability
Functional Programming in Java - Code for Maintainability
 
Hierarchical free monads and software design in fp
Hierarchical free monads and software design in fpHierarchical free monads and software design in fp
Hierarchical free monads and software design in fp
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
Java 8 Stream API (Valdas Zigas)
Java 8 Stream API (Valdas Zigas)Java 8 Stream API (Valdas Zigas)
Java 8 Stream API (Valdas Zigas)
 
Apache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapApache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmap
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
 
java8
java8java8
java8
 
Lessons Learnt With Lambdas and Streams in JDK 8
Lessons Learnt With Lambdas and Streams in JDK 8Lessons Learnt With Lambdas and Streams in JDK 8
Lessons Learnt With Lambdas and Streams in JDK 8
 
A calculus of mobile Real-Time processes
A calculus of mobile Real-Time processesA calculus of mobile Real-Time processes
A calculus of mobile Real-Time processes
 
Reactive stream processing using Akka streams
Reactive stream processing using Akka streams Reactive stream processing using Akka streams
Reactive stream processing using Akka streams
 
operators.ppt
operators.pptoperators.ppt
operators.ppt
 
Overloading of io stream operators
Overloading of io stream operatorsOverloading of io stream operators
Overloading of io stream operators
 
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
 
Development of a Distributed Stream Processing System
Development of a Distributed Stream Processing SystemDevelopment of a Distributed Stream Processing System
Development of a Distributed Stream Processing System
 
VCE Unit 01 (1).pptx
VCE Unit 01 (1).pptxVCE Unit 01 (1).pptx
VCE Unit 01 (1).pptx
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8
 

Mehr von IndicThreads

Http2 is here! And why the web needs it
Http2 is here! And why the web needs itHttp2 is here! And why the web needs it
Http2 is here! And why the web needs itIndicThreads
 
Understanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
Understanding Bitcoin (Blockchain) and its Potential for Disruptive ApplicationsUnderstanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
Understanding Bitcoin (Blockchain) and its Potential for Disruptive ApplicationsIndicThreads
 
Go Programming Language - Learning The Go Lang way
Go Programming Language - Learning The Go Lang wayGo Programming Language - Learning The Go Lang way
Go Programming Language - Learning The Go Lang wayIndicThreads
 
Building Resilient Microservices
Building Resilient Microservices Building Resilient Microservices
Building Resilient Microservices IndicThreads
 
App using golang indicthreads
App using golang  indicthreadsApp using golang  indicthreads
App using golang indicthreadsIndicThreads
 
Building on quicksand microservices indicthreads
Building on quicksand microservices  indicthreadsBuilding on quicksand microservices  indicthreads
Building on quicksand microservices indicthreadsIndicThreads
 
Iot secure connected devices indicthreads
Iot secure connected devices indicthreadsIot secure connected devices indicthreads
Iot secure connected devices indicthreadsIndicThreads
 
Real world IoT for enterprises
Real world IoT for enterprisesReal world IoT for enterprises
Real world IoT for enterprisesIndicThreads
 
IoT testing and quality assurance indicthreads
IoT testing and quality assurance indicthreadsIoT testing and quality assurance indicthreads
IoT testing and quality assurance indicthreadsIndicThreads
 
Building & scaling a live streaming mobile platform - Gr8 road to fame
Building & scaling a live streaming mobile platform - Gr8 road to fameBuilding & scaling a live streaming mobile platform - Gr8 road to fame
Building & scaling a live streaming mobile platform - Gr8 road to fameIndicThreads
 
Internet of things architecture perspective - IndicThreads Conference
Internet of things architecture perspective - IndicThreads ConferenceInternet of things architecture perspective - IndicThreads Conference
Internet of things architecture perspective - IndicThreads ConferenceIndicThreads
 
Cars and Computers: Building a Java Carputer
 Cars and Computers: Building a Java Carputer Cars and Computers: Building a Java Carputer
Cars and Computers: Building a Java CarputerIndicThreads
 
Scrap Your MapReduce - Apache Spark
 Scrap Your MapReduce - Apache Spark Scrap Your MapReduce - Apache Spark
Scrap Your MapReduce - Apache SparkIndicThreads
 
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
 Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & DockerIndicThreads
 
Speed up your build pipeline for faster feedback
Speed up your build pipeline for faster feedbackSpeed up your build pipeline for faster feedback
Speed up your build pipeline for faster feedbackIndicThreads
 
Unraveling OpenStack Clouds
 Unraveling OpenStack Clouds Unraveling OpenStack Clouds
Unraveling OpenStack CloudsIndicThreads
 
Digital Transformation of the Enterprise. What IT leaders need to know!
Digital Transformation of the Enterprise. What IT  leaders need to know!Digital Transformation of the Enterprise. What IT  leaders need to know!
Digital Transformation of the Enterprise. What IT leaders need to know!IndicThreads
 
Architectural Considerations For Complex Mobile And Web Applications
 Architectural Considerations For Complex Mobile And Web Applications Architectural Considerations For Complex Mobile And Web Applications
Architectural Considerations For Complex Mobile And Web ApplicationsIndicThreads
 
Functional Programming With Lambdas and Streams in JDK8
 Functional Programming With Lambdas and Streams in JDK8 Functional Programming With Lambdas and Streams in JDK8
Functional Programming With Lambdas and Streams in JDK8IndicThreads
 
Changing application demands: What developers need to know
Changing application demands: What developers need to knowChanging application demands: What developers need to know
Changing application demands: What developers need to knowIndicThreads
 

Mehr von IndicThreads (20)

Http2 is here! And why the web needs it
Http2 is here! And why the web needs itHttp2 is here! And why the web needs it
Http2 is here! And why the web needs it
 
Understanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
Understanding Bitcoin (Blockchain) and its Potential for Disruptive ApplicationsUnderstanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
Understanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
 
Go Programming Language - Learning The Go Lang way
Go Programming Language - Learning The Go Lang wayGo Programming Language - Learning The Go Lang way
Go Programming Language - Learning The Go Lang way
 
Building Resilient Microservices
Building Resilient Microservices Building Resilient Microservices
Building Resilient Microservices
 
App using golang indicthreads
App using golang  indicthreadsApp using golang  indicthreads
App using golang indicthreads
 
Building on quicksand microservices indicthreads
Building on quicksand microservices  indicthreadsBuilding on quicksand microservices  indicthreads
Building on quicksand microservices indicthreads
 
Iot secure connected devices indicthreads
Iot secure connected devices indicthreadsIot secure connected devices indicthreads
Iot secure connected devices indicthreads
 
Real world IoT for enterprises
Real world IoT for enterprisesReal world IoT for enterprises
Real world IoT for enterprises
 
IoT testing and quality assurance indicthreads
IoT testing and quality assurance indicthreadsIoT testing and quality assurance indicthreads
IoT testing and quality assurance indicthreads
 
Building & scaling a live streaming mobile platform - Gr8 road to fame
Building & scaling a live streaming mobile platform - Gr8 road to fameBuilding & scaling a live streaming mobile platform - Gr8 road to fame
Building & scaling a live streaming mobile platform - Gr8 road to fame
 
Internet of things architecture perspective - IndicThreads Conference
Internet of things architecture perspective - IndicThreads ConferenceInternet of things architecture perspective - IndicThreads Conference
Internet of things architecture perspective - IndicThreads Conference
 
Cars and Computers: Building a Java Carputer
 Cars and Computers: Building a Java Carputer Cars and Computers: Building a Java Carputer
Cars and Computers: Building a Java Carputer
 
Scrap Your MapReduce - Apache Spark
 Scrap Your MapReduce - Apache Spark Scrap Your MapReduce - Apache Spark
Scrap Your MapReduce - Apache Spark
 
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
 Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
 
Speed up your build pipeline for faster feedback
Speed up your build pipeline for faster feedbackSpeed up your build pipeline for faster feedback
Speed up your build pipeline for faster feedback
 
Unraveling OpenStack Clouds
 Unraveling OpenStack Clouds Unraveling OpenStack Clouds
Unraveling OpenStack Clouds
 
Digital Transformation of the Enterprise. What IT leaders need to know!
Digital Transformation of the Enterprise. What IT  leaders need to know!Digital Transformation of the Enterprise. What IT  leaders need to know!
Digital Transformation of the Enterprise. What IT leaders need to know!
 
Architectural Considerations For Complex Mobile And Web Applications
 Architectural Considerations For Complex Mobile And Web Applications Architectural Considerations For Complex Mobile And Web Applications
Architectural Considerations For Complex Mobile And Web Applications
 
Functional Programming With Lambdas and Streams in JDK8
 Functional Programming With Lambdas and Streams in JDK8 Functional Programming With Lambdas and Streams in JDK8
Functional Programming With Lambdas and Streams in JDK8
 
Changing application demands: What developers need to know
Changing application demands: What developers need to knowChanging application demands: What developers need to know
Changing application demands: What developers need to know
 

Kürzlich hochgeladen

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 

Kürzlich hochgeladen (20)

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 

Harnessing the Power of Java 8 Streams

  • 1. Harnessing the power of Java 8 Streams Praveer Gupta
  • 3. helps to make a strategic decision about what programming language should be adopted when starting to build a new software system Java 8 released on Mar 18, 2014
  • 4. –Robert C. Martin “There are two parts to learning craftsmanship: knowledge and work. You must gain the knowledge of principles, patterns, practices, and heuristics that a craftsman knows, and you must also grind that knowledge into your fingers, eyes, and gut by working hard and practicing..”
  • 5. Stream Intermediate Operators Terminal Operators Harnessing the power Java 8 Streams Programming Paradigm Concepts
  • 6. Stream Collectorscollectreduce Intermediate Operators Terminal Operators computation creation Primitive Streams stateless/stateful Lazy & Short-Circuited Harnessing the power Java 8 Streams Declarative Programming Internal Iteration chained categories Programming Paradigm Concepts
  • 7. Harnessing the power Java 8 Streams Declarative Programming Internal Iteration Programming Paradigm Concepts
  • 8. Declarative SELECT NAME FROM PERSON WHERE AGE > 18; List<String> adults = group.stream()
 .filter(p -> p.age() > 18) .map(Person::name)
 .collect(toList()); You declare what the program has to do and the library takes care of how to do it
  • 9. Declarative Focuses on What List<String> adults = new ArrayList<>();
 for (Person person: group) 
 if (person.age() > 18)
 adults.add(person.name()); Focuses on How and What vs Imperative List<String> adults = group.stream()
 .filter(p -> p.age() > 18) .map(Person::name)
 .collect(toList());
  • 10. Old way vs New way final List<String> names = new ArrayList<>();
 for (Person p : group)
 if (p.age() > 18) names.add(p.name());
 return names; return group.stream()
 .filter(p -> p.age() > 18)
 .map(Person::name)
 .collect(toList()); List<String> namesOfAdultsInTheGroup(List<Person> group) { } External Iteration Internal Iteration new declarative way old imperative way List<String> namesOfAdultsInTheGroup(List<Person> group) { }
  • 11. Application of Streams interface CustomerRepository {
 List<Customer> findByCity(String cityName);
 } API Definition
  • 12. Application of Streams interface CustomerRepository {
 Stream<Customer> findByCity(String cityName);
 } try (Stream<String> stream = repository.findByCity(“Pune")) {
 return stream.filter(…).count();
 } API Definition Usage of the API Consume items as they arrive Efficient memory usage
  • 13. Stream computation creation Harnessing the power Java 8 Streams Declarative Programming Internal Iteration Programming Paradigm Concepts
  • 14. Stream a read-only sequence of elements computational operations that will be performed in aggregate Collection efficient management of elements efficient access to elements
  • 16. Stream Terminal Operator Operator1 Operator2 Operator3 Stream Pipeline List<String> namesOfAdultsInTheGroup(List<Person> group) {
 return
 
 
 
 } group.stream() .filter(p -> p.age() > 18) .map(Person::name) .collect(Collectors.toList());
  • 17. names group Stream<Person> Archer (22 years) Barbara (17 years) Daisy (25 years) is person’s age > 18 ? Stream<Person> Stream<String> map to name of person collect into a list group.stream() .filter(p -> p.age() > 18) .map(Person::name) .collect( Collectors.toList()); Archer (22 years) Barbara (17 years) Daisy (25 years) Archer (22 years) Daisy (25 years) Archer Daisy Archer Daisy
  • 18. Creating Stream From Collection List<String> list = Arrays.asList("a", "b", "c");
 Stream<String> stream = list.stream(); String[] array = {"a", "b", "c"};
 Stream<String> stream = Arrays.stream(array);
  • 19. Creating Stream From an I/O Channel try (Stream<Path> stream = Files.list(Paths.get(“.”));) { … } Stream interface extends AutoCloseable
  • 20. Creating Stream Using Generator Functions Stream<Double> stream = Stream.generate(Math::random); Stream<Integer> stream = Stream.iterate(0, n -> n + 3); Both are unbounded
  • 21. Parallel Stream From Collection List<String> list = Arrays.asList("a", "b", "c");
 Stream<String> stream = list.parallelStream(); From another Stream Stream<String> parallelStream = stream.parallel(); List<String> list = Arrays.asList("a", "b", "c");
 Stream<String> stream = list.parallelStream(); Stream<String> parallelStream = stream.parallel();
  • 22. Parallel Stream How does it work? Splitting Combining Parallel Processing
  • 23. Parallel Stream Performance Impact Always measure performance before using parallel Stream size predictability & Amount of data Decomposability of source data structure Computational Cost
  • 24. Stream Intermediate Operators computation creation stateless/stateful Harnessing the power Java 8 Streams Declarative Programming Internal Iteration chained categories Programming Paradigm Concepts
  • 26. Intermediate Operators Categories Stream<Integer> stream = Stream.of(3, 2, 1); Stream<Integer> filtered = stream.filter(n -> n % 2 == 0); Filtering Type of stream remains the same Stream<Integer> filtered = stream.filter(n -> n % 2 == 0);
  • 27. Intermediate Operators Categories Stream<Integer> stream = Stream.of(3, 2, 1); Stream<String> mapped = stream.map(Object::toString); Mapping Type of stream gets altered (here Integer to String) Stream<String> mapped = stream.map(Object::toString);
  • 28. Intermediate Operators Categories Stream<Integer> stream = Stream.of(3, 2, 1); Stream<Integer> sliced = stream.limit(1); Slicing Type of stream remains the same Stream<Integer> sliced = stream.limit(1);
  • 29. Stream.of(1, 2, 3, 4)
 .peek(System.out::println)
 .filter(n -> n % 2 == 0); Intermediate Operators Laziness Stream.of(1, 2, 3, 4)
 .peek(System.out::println)
 .filter(n -> n % 2 == 0)
 .collect(toList()); Stream.of(1, 2, 3, 4)
 .peek(System.out::println)
 .filter(n -> n % 2 == 0); Terminal operator is required to start stream processing Stream.of(1, 2, 3, 4)
 .peek(System.out::println)
 .filter(n -> n % 2 == 0)
 .collect(toList()); Peek will not print anything
  • 30. Intermediate Operators Short-Circuiting Stream.of(1, 2, 3, 4)
 .peek(System.out::println)
 .filter(n -> n % 2 == 0)
 .findFirst(); Stream will get short-circuited after the first element is found Peek will print only 1 & 2 Stream.of(1, 2, 3, 4)
 .peek(System.out::println)
 .filter(n -> n % 2 == 0)
 .findFirst();
  • 31. Intermediate Operators Stateless vs Stateful Stream.of(1, 2, 3, 4)
 .peek(System.out::println)
 .filter(n -> n % 2 == 0)
 .findFirst(); Stream.of(1, 2, 3, 4)
 .peek(System.out::println)
 .sorted(Comparator.reverseOrder())
 .filter(n -> n % 2 == 0)
 .findFirst(); Will cause the whole stream to be traversed All operations are done on current value in stream Stream.of(1, 2, 3, 4)
 .peek(System.out::println)
 .sorted(Comparator.reverseOrder())
 .filter(n -> n % 2 == 0)
 .findFirst();
  • 32. Stream Collectorscollectreduce Intermediate Operators Terminal Operators computation creation stateless/stateful Lazy & Short-Circuited Harnessing the power Java 8 Streams Declarative Programming Internal Iteration chained categories Programming Paradigm Concepts
  • 33. Terminal Operators Single Value Collection Reduce Operation Collect Operation
  • 34. Terminal Operators reduce <U> U reduce(U identity,
 BiFunction<U, ? super T, U> accumulator,
 BinaryOperator<U> combiner); Stream.of(3, 2, 1).reduce(0, Integer::sum, Integer::sum); Stream.of(3, 2, 1).reduce(0, Integer::sum); Immutable Reduction Process <U> U reduce(U identity,
 BiFunction<U, ? super T, U> accumulator,
 BinaryOperator<U> combiner); <U> U reduce(U identity,
 BiFunction<U, ? super T, U> accumulator,
 BinaryOperator<U> combiner); <U> U reduce(U identity,
 BiFunction<U, ? super T, U> accumulator,
 BinaryOperator<U> combiner);
  • 35. Terminal Operators reduce utility methods Optional<Integer> max = Stream.of(1, 2, 3) .max(Comparator.naturalOrder()); boolean result = Stream.of(1, 2, 3) .anyMatch(n -> n > 2); Optional<Integer> max = Stream.of(1, 2, 3) .max(Comparator.naturalOrder()); boolean result = Stream.of(1, 2, 3) .anyMatch(n -> n > 2);
  • 36. Terminal Operators collect Mutable Reduction Process Accumulates elements into a mutable result container Stream.of("a", "b", "c").reduce("", String::concat); String copying = Low Performance !!
  • 37. Terminal Operators collect <R> R collect(Supplier<R> supplier,
 BiConsumer<R, ? super T> accumulator,
 BiConsumer<R, R> combiner); StringBuilder builder = Stream.of("a", "b", "c").collect(
 StringBuilder::new, 
 StringBuilder::append, 
 StringBuilder::append
 ); StringBuilder is the mutable container here
  • 38. Terminal Operators Collectors class String joinedString = Stream.of(“a", "b", “c") .collect(Collectors.joining(", ")); IntSummaryStatistics statistics = group.stream() .collect(Collectors.summarizingInt(Person::age)); IntSummaryStatistics{count=10, sum=280, min=26, average=28.000000, max=30} Output: a, b, c String joinedString = Stream.of(“a", "b", “c") .collect(Collectors.joining(", ")); IntSummaryStatistics statistics = group.stream() .collect(Collectors.summarizingInt(Person::age));
  • 39. Terminal Operators Downstream Collectors Map<Integer, List<Person>> result = group.stream() .collect(Collectors.groupingBy(Person::age,
 Collectors.toList())); Map<Integer, List<Person>> result = group.stream() .collect(groupingBy(Person::age)); Divide into different age groups
  • 40. Terminal Operators Downstream Collectors Map<Integer, Long> result = group.stream() .collect(groupingBy(Person::age, counting())); Map<Integer, List<String>> result = group.stream() .collect(groupingBy(Person::age,
 mapping(Person::name, toList()))); Count of people in each age group Names on people in each age group
  • 41. Stream Collectorscollectreduce Intermediate Operators Terminal Operators computation creation Primitive Streams stateless/stateful Lazy & Short-Circuited Harnessing the power Java 8 Streams Declarative Programming Internal Iteration chained categories Programming Paradigm Concepts
  • 42. Primitive Streams IntStream DoubleStreamLongStream Avoid boxing and unboxing costs Numeric operations are available XXXFunction XXXPredicateXXXSupplierXXXConsumer XXXToXXXFunction Primitive Functional Interfaces
  • 43. Primitive Streams Creating from factory methods IntStream intStream = IntStream.range(1, 10); DoubleStream doubleStream = DoubleStream.of(1.0, 2.0); LongStream longStream = LongStream.iterate(0L, n -> n + 4); Generating a range of numbers Stream of known set of numbers Stream using iterative application of a function
  • 44. Stream<Person> stream = group.stream(); Primitive Streams Obtaining from Stream<T> mapToXXX flatMapToXXX IntStream intStream = stream.mapToInt(Person::age); OptionalDouble averageAge = intStream.average(); Specialized methods on Primitive Streams IntStream intStream = stream.mapToInt(Person::age);
  • 45. Primitive Streams Converting back to Stream<T> Stream<Integer> boxed = IntStream.of(1, 2, 3).boxed();Stream<Integer> boxed = IntStream.of(1, 2, 3).boxed();
  • 46. Stream Collectorscollectreduce Intermediate Operators Terminal Operators computation creation Primitive Streams stateless/stateful Lazy & Short-Circuited Harnessing the power Java 8 Streams Declarative Programming Internal Iteration chained categories Programming Paradigm Concepts