What Is A Stream API
What Is A Stream API
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.
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.
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.
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.
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
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()