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

What Is A Stream API

Introduced in Java 8, streams allow processing of collections of objects. A stream is a sequence of objects that supports intermediate and terminal operations. Intermediate operations such as filter() and map() return a new stream, while terminal operations such as forEach() and collect() terminate the stream and return a result. Streams are lazy and do not change the original collection, instead providing results of pipelined operations on demand.

Uploaded by

jagdish don
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

What Is A Stream API

Introduced in Java 8, streams allow processing of collections of objects. A stream is a sequence of objects that supports intermediate and terminal operations. Intermediate operations such as filter() and map() return a new stream, while terminal operations such as forEach() and collect() terminate the stream and return a result. Streams are lazy and do not change the original collection, instead providing results of pipelined operations on demand.

Uploaded by

jagdish don
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

What is a Stream? Stream vs Collection?

Introduced in Java 8, the Stream API is used to process collections of objects.


A stream is a sequence of objects that supports various methods which can be
pipelined to produce the desired result.

 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.
 Each intermediate operation is lazily executed and returns a stream as a
result, hence various intermediate operations can be pipelined. Terminal
operations mark the end of the stream and return the result.

 If we want to represent a group of objects as a single entity then we should


go for collection.
 But if we want to process objects from the collection then we should go for
streams.

  Stream is available as an interface.


 Stream s = c.stream();
 In the above pre-tag, ‘c’ refers to the collection. So on the collection, we
are calling the stream() method  and at the same time, we are storing it
as the Stream object. Henceforth, this way we are getting the Stream
object.
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.

At the granular level, the difference between a Collection and a Stream is to


do with when the things are computed. A Collection is an in-memory data
structure, which holds all the values that the data structure currently has.

Every element in the Collection has to be computed before it can be added to


the Collection. While a Stream is conceptually a pipeline, in which elements
are computed on demand.

This concept gives rise to significant programming benefits. The idea is that a
user will extract only the values they require from a Stream, and these
elements are produced, invisibly to the user, as and when required. This is a
form of a producer-consumer relationship.
In Java, java.util.Stream interface represents a stream on which one or
more operations can be performed. Stream operations are either
intermediate or terminal.

The terminal operations return a result of a certain type and intermediate


operations return the stream itself so we can chain multiple methods in a row
to perform the operation in multiple steps.

Streams are created on a source, e.g.


a java.util.Collection like List or Set. The Map is not supported directly,
we can create stream of map keys, values or entries.

Stream operations can either be executed sequentially or parallel. when


performed parallelly, it is called a parallel stream.

Based on the above points, a stream is :

 Not a data structure


 Designed for lambdas
 Do not support indexed access
 Can easily be aggregated as arrays or lists
 Lazy access supported
 Parallelizable

Stream In Java
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is
a sequence of objects that supports various methods which can be pipelined to produce
the desired result.
The features of Java stream are –
 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.
 Each intermediate operation is lazily executed and returns a stream as a result, hence
various intermediate operations can be pipelined. Terminal operations mark the end of
the stream and return the result.
Different Operations On Streams-
Intermediate Operations:
The intermediate operations are lazy operations and return a new stream. For example,
executing an intermediate operation such as filter() does not actually perform any filtering, but
instead creates a new stream.

 Java streams are designed in such a way that most of the stream
operations (called intermediate operations) return a Stream. This helps
to create a chain of stream operations. This is called stream pipe-lining.

1. map: The map method is used to returns a stream consisting of the results of applying
the given function to the elements of this stream.
List number = Arrays.asList(2,3,4,5);
List square = number.stream().map(x->x*x).collect(Collectors.toList());
2. filter: The filter method is used to select elements as per the Predicate passed as
argument.
List names = Arrays.asList("Reflection","Collection","Stream");
List result = names.stream().filter(s-
>s.startsWith("S")).collect(Collectors.toList());
3. sorted: The sorted method is used to sort the stream.
List names = Arrays.asList("Reflection","Collection","Stream");
List result = names.stream().sorted().collect(Collectors.toList());

Terminal Operations:
The terminal operations terminate the stream source pipeline after performing the operations.
For example, Stream.forEach or IntStream.sum, may traverse the stream to produce a result.

 Java streams also support the aggregate or terminal operations on


the elements. The aggregate operations are operations that allow us to
express common manipulations on stream elements quickly and clearly,
for example, finding the max or min element, finding the first element
matching giving criteria, and so on.

1. collect: The collect method is used to return the result of the intermediate operations
performed on the stream.
List number = Arrays.asList(2,3,4,5,3);
Set square = number.stream().map(x->x*x).collect(Collectors.toSet());
2. forEach: The forEach method is used to iterate through every element of the stream.
List number = Arrays.asList(2,3,4,5);
number.stream().map(x->x*x).forEach(y->System.out.println(y));
3. reduce: The reduce method is used to reduce the elements of a stream to a single
value.
The reduce method takes a BinaryOperator as a parameter.
List number = Arrays.asList(2,3,4,5);
int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);
Here ans variable is assigned 0 as the initial value and i is added to it .
Program to demonstrate the use of Stream

//a simple program to demonstrate the use of stream in java

1. import java.util.*;
2. import java.util.stream.*;
3.   
4. class Demo
5. {
6.   public static void main(String args[])
7.   {
8.   
9.     // create a list of integers
10.     List<Integer> number = Arrays.asList(2,3,4,5);
11.   
12.     // demonstration of map method
13.     List<Integer> square = number.stream().map(x -> x*x).
14.                            collect(Collectors.toList());
15.     System.out.println(square);
16.   
17.     // create a list of String
18.     List<String> names =
19.                 Arrays.asList("Reflection","Collection","Stream");
20.   
21.     // demonstration of filter method
22.     List<String> result = names.stream().filter(s->s.startsWith("S")).
23.                           collect(Collectors.toList());
24.     System.out.println(result);
25.   
26.     // demonstration of sorted method
27.     List<String> show =
28.             names.stream().sorted().collect(Collectors.toList());
29.     System.out.println(show);
30.   
31.     // create a list of integers
32.     List<Integer> numbers = Arrays.asList(2,3,4,5,2);
33.   
34.     // collect method returns a set
35.     Set<Integer> squareSet =
36.          numbers.stream().map(x->x*x).collect(Collectors.toSet());
37.     System.out.println(squareSet);
38.   
39.     // demonstration of forEach method
40.     number.stream().map(x->x*x).forEach(y->System.out.println(y));
41.   
42.     // demonstration of reduce method
43.     int even =
44.        number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);
45.   
46.     System.out.println(even);
47.   }
48. }

Output:
[4, 9, 16, 25]
[Stream]
[Collection, Reflection, Stream]
[16, 4, 9, 25]
4
9
16
25
6
Important Points/Observations:
1. A stream consists of source followed by zero or more intermediate methods combined
together (pipelined) and a terminal method to process the objects obtained from the
source as per the methods described.
2. Stream is used to compute elements as per the pipelined methods without altering the
original value of the object.

 Intermediate Operations
 filter()
 map()
 flatMap()
 distinct()
 sorted()
 peek()
 limit()
 skip()

7.3. Terminal Operations


 forEach()
 forEachOrdered()
 toArray()
 reduce()
 collect()
 min()
 max()
 count()
 anyMatch()
 allMatch()
 noneMatch()
 findFirst()
 findAny()

You might also like