Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

20ES3102 – Java Programming

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

 Method1: using of()

Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9);


stream.forEach(p -> System.out.println(p));

Method2 using collection object

List<Integer> list = new ArrayList<Integer>();

for(int i = 1; i< 10; i++){


list.add(i);
}

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.

memberNames.stream().filter((s) -> s.startsWith("A"))

.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.

memberNames.stream().filter((s) -> s.startsWith("A"))

.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 #.

Optional<String> reduced = memberNames.stream()

.reduce((s1,s2) -> s1 + "#" + s2);

reduced.ifPresent(System.out::println);

 collect()
The collect() method is used to receive elements from a stream and store them in a
collection.

List<String> memNamesInUppercase = memberNames.stream().sorted()

.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.

long totalMatched = memberNames.stream()

.filter((s) -> s.startsWith("A"))

.count();

System.out.println(totalMatched);

 min()
 max()

Sample program on streamAPI


import java.util.*;

import java.util.stream.*;

class StreamAPI

public static void main(String args[])

// creating stream Method 1 using 0f()

Stream<String> stream1 = Stream.of("first","Second","third","fourth");

//Travelling over stream (Terminal Operation)

stream1.forEach(p -> System.out.println(p));


Mr.Raghu Virapratap
14
Asst. Professor
CSE Dept, V.R.S.E.C
//creating stream Method2

List<String> list = new ArrayList<String>();

list.add("one");

list.add("two");

list.add("three");

Stream<String> stream2 = list.stream();

stream2.forEach(p -> System.out.println(p));

//Intermediate methods--->filter()

list.stream().filter((s) -> s.startsWith("t"))

.forEach(System.out::println);

//Intermediate methods--->map()

list.stream().filter((s) -> s.startsWith("t")).map(String::toUpperCase)

.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.

Sample program for reduction operation using reduce()


import java.util.*;

class reduceEx

public static void main(String args[])

Mr.Raghu Virapratap
18
Asst. Professor
CSE Dept, V.R.S.E.C
// Normal Approch to find sum value

int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

int sum = 0;

for (int i : numbers)

sum += i;

System.out.println("sum : " + sum);

// Using stream.reduce() method-----> reduction operation

int add = Arrays.stream(numbers).reduce(0, (a, b) -> a + b);

System.out.println("sum : " + add);

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 Example 1:

.*;

import java.util.stream.*;

import java.util.stream.IntStream;

Mr.Raghu Virapratap
23
Asst. Professor
CSE Dept, V.R.S.E.C
class parllel1

public static void main(String[] args)

List<Integer> list = new ArrayList<Integer>();

for(int i = 1; i< 10; i++)

list.add(i);

//Here creating a parallel stream

Stream<Integer> stream = list.parallelStream();

Integer[] even = stream.filter(i -> i%2 == 0).toArray(Integer[]::new);

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

public static void main(String[] args)

System.out.println("Normal...");

IntStream range = IntStream.rangeClosed(1, 10);

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

System.out.println("Parallel...");

IntStream range2 = IntStream.rangeClosed(1, 10);

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

1. Stream to List using collect()

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());

2. Stream to Set using Collector.toSet() method

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()

You can create a Map from elements of Stream.

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

Map<String, Integer> stringToLength

= listOfString

.stream()

.collect( Collectors.toMap(Function.identity(), String::length));

4. Stream to Collection using Collectors.toCollection()

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.

It simply used to convert Stream of one type to another.

Let's see method signature of Stream's map method.

<R> Stream<R> map(Function<? super T,? extends R>mapper)

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.

Inerrable and streams

Converting Iterable to Stream


The Iterable interface is designed keeping generality in mind and does not provide
any stream() method on its own.
Simply put, you can pass it to StreamSupport.stream() method and get a Stream from the
given Iterable instance.
Example:
public void whenConvertedToList_thenCorrect()
{
Iterable<String> iterable
= Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");

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

You might also like