0% found this document useful (0 votes)
10 views

Day19 StreamApi

Uploaded by

mohamedjaaved19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Day19 StreamApi

Uploaded by

mohamedjaaved19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

StreamAPI

TNS India Foundation | ‹#›


Partners in Economic Transformation
Recap

● Functional Interface - It is declared with only one abstract method


● Lambda Expression - It is an anonymous or unnamed method
● Syntax :
● (parameter list) - >lambda body

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q1. Which one of these is the correct Java Lambda Expression Syntax ?

A (argument-list) -> {body}

B argument-list -> {body}

C () -> {body}

D (argument-list) . {body}

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q1. Which one of these is the correct Java Lambda Expression Syntax ?

A (argument-list) -> {body}

B argument-list -> {body}

C () -> {body}

D (argument-list) . {body}

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q2. Java lambda expression is consist which of the following components.

A Argument List

B Arrow Token

C Body

D All

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q2. Java lambda expression is consist which of the following components.

A Argument List

B Arrow Token

C Body

D All

TNS India Foundation | ‹#›


Partners in Economic Transformation
Learning Objective

● Explore the fundamentals of the Stream API in Java.


● Understand the essential characteristics of streams.
● Delve into intermediate operations available in streams.
● Learn about terminal operations and their significance.
● Gain practical experience in working with streams through hands-on coding exercises.
● Master techniques such as mapping, filtering, and reducing data with streams.
● Examine examples showcasing various terminal operations.
● Discover the benefits of utilizing streams in Java programming.
● Explore real-time examples demonstrating the practical applications of streams.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Hook

TNS India Foundation | ‹#›


Partners in Economic Transformation
Introduction to the current topic

● Stream API is used to process collections of objects.


● A stream in Java is a sequence of objects that supports various methods which can be pipelined
to produce the desired result.
● Stream API is a way to express and process collections of objects.
● Enable us to perform operations like filtering, mapping,reducing and sorting.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Why Stream API?

● Enhances the usability of Java Collection types, making it easy to iterate and perform tasks against
each element in the collection
● Supports sequential and parallel aggregate operations
● Stream API allows developers process data in a declarative way

TNS India Foundation | ‹#›


Partners in Economic Transformation
Characteristics of Stream

● Not a data structure:Streams have no storage. They carry values from a source
through a pipeline of operations.
● Designed for lambdas :All Stream operations take lambdas as arguments
● Do not support indexed access :
● Can easily be output as arrays or Lists
● Lazy :Many Stream operations are postponed until it is known how much data is
eventually needed
● Parallelizable :If you designate a Stream as parallel, then operations on it will
automatically
● Can be unbounded:Unlike with collections, you can designate a generator
function, and clients can consume entries as long as they want, with values being
generated on the fly

TNS India Foundation | ‹#›


Partners in Economic Transformation
Current Topic (Explanation)
● A stream is not a data structure instead it takes input from the Collections,
Arrays or I/O channels.
● Streams don’t change the original data structure, they only provide the result as
per the pipelined methods.
● A stream represents a sequence of elements and supports different operations
(Filter, Sort, Map, and Collect) from a collection.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Key Points

● Stream defines many operations, which can be grouped in two categories


● Intermediate operations
● Terminal Operations
● Stream operations that can be connected are called intermediate operations.
● They can be connected together because their return type is a Stream
● Operations that close a stream pipeline are called terminal operations.
● Intermediate operations are “lazy

TNS India Foundation | ‹#›


Partners in Economic Transformation
Intermediate Operations

● When an operation on a stream further produces another stream as a result, we call it


an intermediate operation.
● As intermediate operations return another stream as a result, they can be chained
together to form a pipeline of operations.
● As the word ‘intermediate’ suggest, these operations doesn’t give end result.
● They just convert one stream to another stream.
● For example: map(), filter(), distinct(), sorted(), limit(), skip()

TNS India Foundation | ‹#›


Partners in Economic Transformation
Terminal Operations

● The operations which return non-stream values such as primitive or object are called
terminal operations.
● Furthermore, unlike intermediate operations, we can’t chain them together.
● They produce the end result.
● Once a terminal operation completes, the Stream is no longer valid.
● Hence, we can’t use that stream again.
● For example : forEach(), toArray(), reduce(), collect(), min(), max(), count(),
anyMatch(), allMatch(), noneMatch(), findFirst(), findAny()
● Stream processing consists of a series of zero or more intermediate operations
followed by a terminal operation.
● Each intermediate operation returns a new stream. The terminal operation returns
something other than a stream.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Working with Stream: Step - 1

● To perform a computation, first we need to define source of stream To create a stream


source from values, use “of ” method
Stream stream = Stream.of(10,20,30);
● A stream can be obtained from sources like arrays or collections using “stream”
method.
● To obtain steam from array, use java.util.Arrays class
stream()
● To obtain stream from collections, use java.util.Collection interface
● stream()
● parallelStream()

TNS India Foundation | ‹#›


Partners in Economic Transformation
Working with Stream: Step - 2

● A stream pipeline consist of source, zero or more intermediate operations and a


terminal operation
● A stream pipeline can be viewed as a query on the stream source Operations on
stream are categories as:
Filter
Map
Reduce
Search
Sort

TNS India Foundation | ‹#›


Partners in Economic Transformation
Hands On Coding

TNS India Foundation | ‹#›


Partners in Economic Transformation
How to print a Stream?

● When our code doesn’t work as expected, either we add a println() statement or go with
setting a breakpoint to see the values of an object.
● Since intermediate operations don’t return something until needed, printing is not a
straightforward process with the streams.
● Therefore, we need to apply some particular approaches to print the values.

s.forEach(System.out::println);

System.out.println(s.collect(Collectors.toList()));

s.limit(4).forEach(System.out::println);

s.peek(System.out::println).count();
TNS India Foundation | ‹#›
Partners in Economic Transformation
Mapping

● The Stream interface's map method maps each element of stream with the result of
passing the element to a function.
● Map() takes a function (java.util.function.Function) as an argument to project the
elements of a stream into another form.
● The function is applied to each element, “mapping” it into a new element.
Syntax:

● The map method returns a new Stream of elements whose type may be different from
the type of the elements of the current stream.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Filtering

● A stream can be filtered out by using filter() method on Stream interface.


● Its takes predicate as argument which is usually a criteria for filtering, and returns new
filtered stream containing elements which satisfies the criteria.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Filtering

TNS India Foundation | ‹#›


Partners in Economic Transformation
Reduce

● The reduce operation on streams, which repeatedly applies an operation on each


element until a result is produced.
● It’s often called a fold operation in functional programming.
● The reduce () method takes a BinaryOperator as argument and returns an Optional
instance

TNS India Foundation | ‹#›


Partners in Economic Transformation
Terminal operation examples

TNS India Foundation | ‹#›


Partners in Economic Transformation
Hands On Coding

TNS India Foundation | ‹#›


Partners in Economic Transformation
Benefits or Uses

● Stream API allows developers process data in a declarative way.


● Streams can leverage multicore architectures without writing a single line of multi
threaded code
● Enhances the usability of Java Collection types, making it easy to iterate and perform
tasks against each element in the collection
● Supports sequential and parallel aggregate operations more complex data processing
logics with the least number of lines of code.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Real Time Example

● All of us have watched online videos on Youtube.


● When we start watching a video, a small portion of the video file is first loaded into our
computer and starts playing.
● we don’t need to download the complete video before we start watching it. This is
called video streaming.
● At a very high level, we can think of the small portions of the video file as a stream and
the whole video as a Collection.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Hands on Coding

TNS India Foundation | ‹#›


Partners in Economic Transformation
Activity:Filtering and Summing Even Numbers

iimport java.util.Arrays;
import java.util.List;

public class StreamExample {


public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

int sumOfEvenNumbers = numbers.stream()


.________(num -> num % 2 == 0)
._______(Integer::intValue)
.sum();

System.out.println("Sum of even numbers: " + sumOfEvenNumbers);


}
}

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q1. What are the two types of Streams offered by java 8?

A Sequential and Parallel

B Sequential and Random

C Parallel and Random

D Random and Synchronized

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q1. What are the two types of Streams offered by java 8?

A Sequential and Parallel

B Sequential and Random

C Parallel and Random

D Random and Synchronized

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q2. Which method is used to transform each element of a Stream using a provided
function?

A filter

B map

C reduce

D filterMap

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q2. Which method is used to transform each element of a Stream using a provided
function?

A filter

B map

C reduce

D filterMap

TNS India Foundation | ‹#›


Partners in Economic Transformation
Summary

● Explore the fundamentals of the Stream API in Java.


● Understand the essential characteristics of streams.
● Delve into intermediate operations available in streams.
● Learn about terminal operations and their significance.
● Gain practical experience in working with streams through hands-on coding exercises.
● Master techniques such as mapping, filtering, and reducing data with streams.
● Examine examples showcasing various terminal operations.
● Discover the benefits of utilizing streams in Java programming.
● Explore real-time examples demonstrating the practical applications of streams.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Assignment Question

Problem statement:
You are working on a social media analytics platform where you need to analyze user posts.
Each post has a content string and a timestamp. Your task is to implement a Java program
that performs the following tasks:
1. Create a list of Post objects, where each Post has a content string and a timestamp.
2. Filter out any posts that were posted before a specific date and time.
3. Map each remaining post to its content.
4. Split the content of each post into individual words.
5. Count the frequency of each word across all the posts.
6. Collect the word frequencies into a map, where the word is the key and the frequency is
the value.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Assignment Question
Your task is to write the code that implements the above requirements using the Stream API.
Note that you should use the functional programming approach and chaining of stream
operations to achieve the desired result. This scenario represents a real-time application
where you can analyze user posts and gain insights from the data
Input Format
The first line of input is an integer representing the number of posts.
The second line of input is a string representing the content for post.
The third line of input is a date representing the Timestamp (YYYY-MM-DD HH:MM) for
post.
The fourth line of input is a date representing the filter date and time (YYYY-MM-DD
HH:MM).
Output Format
The output displays the word and word frequencies.
TNS India Foundation | ‹#›
Partners in Economic Transformation
Sample input 1 Sample Output 1

4 Word: new, Frequency: 1


Hello, everyone! How are you doing? Word: launch!, Frequency: 1
2022-05-01 09:15 Word: celebrate, Frequency: 1
I'm excited about the new features.
Word: don't, Frequency: 1
2022-05-02 13:45
Don't forget to join our webinar tomorrow. Word: excited, Frequency: 1
2022-05-03 17:30 Word: let's, Frequency: 1
Let's celebrate the launch! Word: about, Frequency: 1
2022-05-04 11:20 Word: our, Frequency: 1
2022-05-02 00:00 Word: i'm, Frequency: 1
Word: the, Frequency: 2
Word: forget, Frequency: 1
Word: tomorrow., Frequency: 1
Word: join, Frequency: 1
TNS India Foundation | ‹#›
Partners in Economic Transformation
Word: to, Frequency: 1
Let’s Reflect -

1. What is your major learning from today’s session?


2. How are you going to use this learning in your journey on the job?

TNS India Foundation | ‹#›


Partners in Economic Transformation

You might also like