20ES3102 Java Programming Unit IV Chapter 3 Stream API
20ES3102 Java Programming Unit IV Chapter 3 Stream API
UNIT-IV
Chapter 3 : The Stream API
Stream API
Mr.Raghu Virapratap
1
Asst. Professor
CSE Dept, V.R.S.E.C
Mr.Raghu Virapratap
2
Asst. Professor
CSE Dept, V.R.S.E.C
Mr.Raghu Virapratap
3
Asst. Professor
CSE Dept, V.R.S.E.C
Mr.Raghu Virapratap
4
Asst. Professor
CSE Dept, V.R.S.E.C
Mr.Raghu Virapratap
5
Asst. Professor
CSE Dept, V.R.S.E.C
Mr.Raghu Virapratap
6
Asst. Professor
CSE Dept, V.R.S.E.C
Mr.Raghu Virapratap
7
Asst. Professor
CSE Dept, V.R.S.E.C
Mr.Raghu Virapratap
8
Asst. Professor
CSE Dept, V.R.S.E.C
Mr.Raghu Virapratap
9
Asst. Professor
CSE Dept, V.R.S.E.C
Mr.Raghu Virapratap
10
Asst. Professor
CSE Dept, V.R.S.E.C
Summary
Stream Operations
1 Creating Streams
Mr.Raghu Virapratap
11
Asst. Professor
CSE Dept, V.R.S.E.C
Stream<Integer> stream = list.stream();
stream.forEach(p -> System.out.println(p));
2 Intermediate Operations
filter()
The filter() method accepts a Predicate to filter all elements of the stream. This operation is
intermediate which enables us to call another stream operation (e.g. forEach()) on the result.
.forEach(System.out::println);
map()
The map() intermediate operation converts each element in the stream into another object
via the given function.
The following example converts each string into an UPPERCASE string. But we can
use map() to transform an object into another type as well.
.map(String::toUpperCase)
.forEach(System.out::println);
sorted()
The sorted() method is an intermediate operation that returns a sorted view of the
stream.
MemberNames.stream().sorted()
.map(String::toUpperCase)
.forEach(System.out::println);
Mr.Raghu Virapratap
12
Asst. Professor
CSE Dept, V.R.S.E.C
3. Terminal Operations
forEach()
The forEach() method helps in iterating over all elements of a stream and perform some
operation on each of them. The operation to be performed is passed as the lambda
expression.
memberNames.forEach(System.out::println);
reduce()
The reduce() method performs a reduction on the elements of the stream with the given
function. The result is an Optional holding the reduced value.
In the given example, we are reducing all the strings by concatenating them using a
separator #.
reduced.ifPresent(System.out::println);
collect()
The collect() method is used to receive elements from a stream and store them in a
collection.
.map(String::toUpperCase)
.collect(Collectors.toList());
Mr.Raghu Virapratap
13
Asst. Professor
CSE Dept, V.R.S.E.C
count()
The count() is a terminal operation returning the number of elements in the stream as
a long value.
.count();
System.out.println(totalMatched);
min()
max()
import java.util.stream.*;
class StreamAPI
list.add("one");
list.add("two");
list.add("three");
//Intermediate methods--->filter()
.forEach(System.out::println);
//Intermediate methods--->map()
.forEach(System.out::println);
//Intermediate methods--->sorted()
list.stream().sorted()
.forEach(System.out::println);
Mr.Raghu Virapratap
15
Asst. Professor
CSE Dept, V.R.S.E.C
Mr.Raghu Virapratap
16
Asst. Professor
CSE Dept, V.R.S.E.C
Mr.Raghu Virapratap
17
Asst. Professor
CSE Dept, V.R.S.E.C
Reduction operation
Reducing in the context of Java 8 Streams refers to the process of combining all elements in the stream
repeatedly to produce a single value which is returned as the result of the reduction operation.
reduce() method is used to perform reduction operations on streams of data.
Given a stream of elements there could be various ways in which one can reduce (or combine)
them to a single resultant value such as summation of all elements (for numeric types), finding
the maximum element from among all the elements (based on the elements’ comparison order),
and similar operations for combining multiple elements into a single resultant value.
class reduceEx
Mr.Raghu Virapratap
18
Asst. Professor
CSE Dept, V.R.S.E.C
// Normal Approch to find sum value
int sum = 0;
sum += i;
Mr.Raghu Virapratap
19
Asst. Professor
CSE Dept, V.R.S.E.C
Mr.Raghu Virapratap
20
Asst. Professor
CSE Dept, V.R.S.E.C
Mr.Raghu Virapratap
21
Asst. Professor
CSE Dept, V.R.S.E.C
Using parallel streams
Mr.Raghu Virapratap
22
Asst. Professor
CSE Dept, V.R.S.E.C
To enable parallelism, all we have to do is to create a parallel stream, instead of a
sequential stream.
anytime we want to do a particular job using multiple threads in parallel cores, all we
have to call parallelStream() method instead of stream() method or parallel().
.*;
import java.util.stream.*;
import java.util.stream.IntStream;
Mr.Raghu Virapratap
23
Asst. Professor
CSE Dept, V.R.S.E.C
class parllel1
list.add(i);
System.out.print(even);
Example 2:
import java.util.*;
Mr.Raghu Virapratap
24
Asst. Professor
CSE Dept, V.R.S.E.C
import java.util.stream.*;
import java.util.stream.IntStream;
class parllel
System.out.println("Normal...");
range.forEach(System.out::println);
System.out.println("Parallel...");
range2.parallel().forEach(System.out::println);
Mr.Raghu Virapratap
25
Asst. Professor
CSE Dept, V.R.S.E.C
Collecting/ Collecter
The Collector class provides different methods like toList(), toSet(), toMap(),
and toConcurrentMap() to collect the result of Stream into List, Set, Map, and
ConcurrentMap in Java.
It also provides a special toCollection() method which can be used to collect Stream
elements into a specified Collection like ArrayList, Vector, LinkedList, or HashSet.
Stream's collect() method to collect the result of stream processing into a List, Set, and Map
in Java
This is the first example of using the Stream.collect() method where we will collect the result of
the stream pipeline in a List. You can collect the result of a Stream processing pipeline in a list
by using the Collectors.toList() method. Just pass the Collectors.toList() to collect() method as
shown below:
List<String> res:
= listOfString
.stream()
.filter( s -> s.startsWith("J"))
.collect(Collectors.toList());
This is the second example of the collect() method of Stream class where we will collect the
result of the Stream pipeline into a Set.
You can use Collectors.toSet() method along with collect() to accumulate elements of a Stream
into a Set.
Mr.Raghu Virapratap
26
Asst. Professor
CSE Dept, V.R.S.E.C
3. Stream to Map using toMap()
using collect() and Collectors.toMap() method. Since a Map like HashMap stores two objects i.e.
key and value and Stream contains just one element, you need to provide the logic to extract the
key and value objects from the Stream elemen
= listOfString
.stream()
You can also collect or accumulate the result of Stream processing into a Collection of your
choices like ArrayList, HashSet, or LinkedList.
There is also a toCollection() method in the Collectors class that allows you to convert Stream to
any collection. In the following example, we will learn how to collect Stream elements into an
ArrayList.
ArrayList<String> stringWithLengthGreaterThanTwo
= listOfString
.stream()
.filter( s -> s.length() > 2)
.collect(Collectors.toCollection(ArrayList::new));
Mr.Raghu Virapratap
27
Asst. Professor
CSE Dept, V.R.S.E.C
Mapping
map method is intermediate operation and consumes single element from input Stream
and produces single element to output Stream.
Map applies the mapper function on input Stream and generates the output Stream.
Here mapper function is functional interface which takes one input and provides one
output.
List<String> result =
StreamSupport.stream(iterable.spliterator(), false)
.map(String::toUpperCase)
.collect(Collectors.toList());
Mr.Raghu Virapratap
28
Asst. Professor
CSE Dept, V.R.S.E.C
assertThat(
result, contains("TESTING", "ITERABLE", "CONVERSION", "TO",
"STREAM"));
}
Mr.Raghu Virapratap
29
Asst. Professor
CSE Dept, V.R.S.E.C