100% found this document useful (1 vote)
165 views

Advanced Java Unit 3 Digital Notes

Uploaded by

23102208
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
165 views

Advanced Java Unit 3 Digital Notes

Uploaded by

23102208
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

1

2
Please read this disclaimer before proceeding:
This document is confidential and intended solely for the
educational purpose of RMK Group of Educational Institutions. If you have
received this document through email in error, please notify the system
manager. This document contains proprietary information and is intended
only for the respective group/learning community as intended. If you
are not the addressee you should not disseminate, distribute, or copy
through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from
your system. If you are not the intended recipient you are notified that
disclosing, copying, distributing, or taking any action in reliance on
the contents of this information is strictly prohibited.

3
22CS305
Advanced Java Programming
(Lab Integrated)
Department : CSE/IT/ADS/CSD/CSBS/ECE
Batch / Year : 2023 – 2027 / II
Created by : All Subject Handling Staff Members
Date : 29.06.2024

4
Table of Contents
Page
Sl.No. Topic
No.

1 Course Objectives 6

2 Syllabus 7

3 Pre-requisites 10

4 Course Outcomes 11

5 CO- PO Mapping 12

6 Lecture Plan 13

7 Activity-based learning 14

8 Lecture Notes 15

9 Assignments I - V 71 - 75

10 Part A Questions & Answers 76

11 Part B Questions 78

12 Supportive Online Certifications 79

13 Real-Time Applications 80

14 Content Beyond the Syllabus 81

15 Assessment Schedule 84

16 Prescribed Text Books & Reference Books 85

17 Mini Projects I - V 86-93

5
1. Course Objectives

OBJECTIVES: ( To be updated )

The Course will enable learners to:

 Gain a comprehensive understanding of the Java Collections Framework and its various

interfaces and implementations.

 Learn the details of Java I/O streams and utility classes for managing dates, numbers, and

currencies.

 Develop a thorough understanding of the Stream API introduced in Java 8 and its various

operations.

 Explore advanced object serialization and string tokenizing techniques, including pattern

matching with regular expressions.

 Understand advanced Stream API features and gain proficiency in using regular expressions

for text processing.

6
2. Syllabus
22CS305 ADVANCED JAVA PROGRAMMING (LAB INTEGRATED) L T P C
3 0 2 4
UNIT I COLLECTIONS FRAMEWORK AND UTILITY CLASSES 9+6
Introduction to Collections Framework - Collection Interface- Methods in Collection
Interface - - Iterable and Iterator Interfaces - List Interface- ArrayList - LinkedList - Set
Interface - HashSet- LinkedHashSet - TreeSet - Map Interface - HashMap -
LinkedHashMap- TreeMap - Queue Interface -PriorityQueue - Deque Interface - Utility
Classes.
List of Exercises
1. Write a program that measures the time taken for insertion, deletion, and search
operations on ArrayList, LinkedList, HashSet, and TreeSet for varying sizes of input data.
2. Implement a custom data structure that combines features of a list and a set.
3. Write a Java program to create a HashMap where the keys are strings, and the values
are integers Add five key-value pairs to the map. Print all the keys and values in the
map. Remove an entry by key. Update the value associated with a specific key. Check
if the map contains a specific key and a specific value.
UNIT II I/O OPERATIONS, SERIALIZATION, AND DATE HANDLING 9+6
Date – Calendar – Comparable interface – Observer Interface – Streams - Types of
Streams - The Byte-stream I/O hierarchy - Character Stream Hierarchy – Random
Access File class – the java.io. Console Class – Serialization – Dates - Numbers, and
Currency - Working with Dates - Numbers and Currencies.
List of Exercises
1. Create a class representing a complex object with nested data structures.
Serialize the object to a file, then deserialize it back and verify that the object
remains intact.

2. Write a program that formats dates and currencies according to different locales.
3. Implement a java program that allows users to open a text file, navigate through
it using random access, insert, delete, and modify text at specific positions within the
file.

7
UNIT III STREAM API AND FUNCTIONAL PROGRAMMING 9+6
PARADIGMS
Overview of Stream API - Importance of Stream API in Java 8 and Beyond – Functional
Programming Concepts - Creating Streams - Stream Interface Methods - Stream
Operations- Intermediate Filtering (filter)-Mapping (map, flatMap)-Sorting (sorted)-
Distinct (distinct)- Limit and Skip (limit, skip) - Terminal Operations -Collecting Results
(collect) - Reducing and Summarizing (reduce, summaryStatistics)-Iterating (forEach) -
Matching and Finding (anyMatch, allMatch, noneMatch, findFirst, findAny) -Counting
(count).

List of Exercises
1. Write a program that performs stream operations like filtering, mapping, and reducing.
2. Create an infinite stream generator that generates prime numbers. Implement
methods to check for primality and generate the next prime number.
3. Write a program that reads a text file containing sentences. Tokenize each sentence into
words, filter out stopwords, and print the remaining words.
UNIT IV ADVANCED STRING PROCESSING, OBJECT SERIALIZATION, 9+6
AND I/O TECHNIQUES
String Tokenizer – Parsing - Tokenizing and Formatting - Locating Data via Pattern
Matching, Tokenizing - Object Serialization - Serializable Interface - Writing and Reading
Serializable Objects -Transient Keyword- SerialVersionUID - Advanced I/O - Piped
Streams (PipedInputStream and PipedOutputStream) – SequenceInputStream –
PushbackInputStream and PushbackReader.

List of Exercises
1. Write a program that reads a text file and tokenizes it into sentences using the
StringTokenizer class.
2. Create a class hierarchy representing different types of objects (e.g., Person,
Employee). Serialize instances of these classes to a file using object serialization.
3. Implement a program that uses advanced I/O techniques like PipedInputStream,
PipedOutputStream, SequenceInputStream, and PushbackInputStream.

8
UNIT V ADVANCED STREAM FEATURES AND REGULAR EXPRESSIONS 9+6
Importance and Use Cases of Advanced Stream Features - Creating Custom Streams –
Stream Generators (Stream.generate, Stream.iterate) - Infinite Streams -Using
Spliterators – Advanced Stream Operations - FlatMapping - Chaining Stream Operations
- Stream Peeking (peek) - Advanced Filtering Techniques- Introduction to Regular
Expressions - Character Classes - Quantifiers - Pattern Matching - Groups and Capturing

- Regex in Java - java.util.regex Package Pattern Class - Matcher Class - String


Manipulation with Regex - Splitting Strings - Replacing Text (replaceAll, replaceFirst) -
Replacing with Backreferences.

List of Exercises
1. Implement custom stream generators using Stream.generate and Stream.iterate
methods.
2. Write a program that demonstrates advanced stream operations like flatMapping,
chaining stream operations, and peeking.

3. Develop a program that utilizes regular expressions to perform string manipulation

tasks such as splitting strings, replacing text, and extracting specific patterns.

TOTAL: 45+30=75 PERIODS

TEXT BOOKS:
1. Cay S. Horstmann, "Core Java Volume I--Fundamentals," 12th Edition, 2019.
2. Joshua Bloch, "Effective Java," 3rd Edition, 2018.
3. Raoul-Gabriel Urma, "Java 8 in Action: Lambdas, Streams, and Functional-Style
Programming," 1st Edition, 2014.

4. Herbert Schildt, "Java: The Complete Reference," 11th Edition, 2018.


5. Alan Mycroft and Martin Odersky, "Programming in Scala," 4th Edition, 2020.

REFERENCES:
1. Bruce Eckel, "Thinking in Java," 4th Edition, 2006.
2. Herbert Schildt, "Java: A Beginner's Guide," 8th Edition, 2019.
3. Richard Warburton, "Java 8 Lambdas: Pragmatic Functional Programming”,
1st Edition, 2014.

9
3. Pre-requisites

22CS305 Advanced Java Programming

22CS202 – Java programming

22CS101 – problem solving using C++

10
4. Course Outcomes
At the end of this course, the students will be able to:

CO# Course Outcomes KL

Utilize the Java Collections Framework to solve complex data structure


CO1 K3
problems..
Demonstrate proficiency in Java I/O operations and manage data
CO2 K3
efficiently.
Learn to utilize the Stream API for complex data processing by applying
CO3 K3
functional programming techniques..

CO4 Understand and implement advanced object serialization techniques. K3

CO5 Effectively use regular expressions for advanced text processing tasks. K3

CO6 Build simple applications using advanced java programming concepts. K3

11
5. CO-PO Mapping

Program Status
Program Outcomes
Course Outcomes
Outcomes PO PO PO PO PO PO PO PO PO PO PO PO PSO PSO PSO
1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
CO1 3 3 3 - - - - - - - - - 3 2 2

CO2 3 2 2 - - - - - - - - - 3 3 2

CO3 3 2 2 - - - - - - - - - 3 3 2

CO4 3 2 2 - - - - - - - - - 3 3 2

CO5 3 2 2 - - - - - - - - - 3 3 2

CO6 3 2 2 - - - - - - - - - 3 3 2

12
6. LECTURE PLAN
Sl. Taxono
No. of. Proposed Actual Pertaining Mode of
No Topics my
. Periods Date Date CO Delivery
Level
As per
As per
Time
Time table
table MD 1,
1,2 2 & CO1, CO6 K3
& MD 4
Academic
Academic
Calendar
Calendar
As per
As per
Time
Time table
table MD 1,
3 1 & & CO1,CO6 K3
MD 4
Academic Academic
Calendar Calendar
As per
As per
Time
Time table
table MD 1,
4 1 & & CO1, CO6 K3
MD 4
Academic Academic
Calendar Calendar
As per
As per
Time
Time table
table MD 1,
5 1 & & CO1, CO6 K3
MD 4
Academic Academic
Calendar Calendar
As per
As per
Time
Time table
table MD 1,
6,7 2 & & CO1, CO6 K3
MD 4
Academic Academic
Calendar Calendar
As per
As per
Time
Time table
table MD 1,
8 1 & & CO1, CO6 K3
MD 4
Academic Academic
Calendar Calendar
As per
As per
Time
Time table
table MD 1,
9 1 & & CO1, CO6 K3
MD 4
Academic Academic
Calendar Calendar
As per
As per
Time
10 Time table
table
- 6 & & CO1, CO6 K3 iamneo
15 Academic Academic
Calendar Calendar
* MD1 – Oral Presentation
13
* MD 4 – Hands on using any Java IDE
7. Activity Based Learning
Common Activities

Learning Methods Activities

Class Exercises, Challenge Yourself,


Learn by Solving Problems Practice At Home exercises posted in
iamneo Portal

Knowledge Check / MCQ Using


Learn by Questioning
iamneo portal and RMK Nextgen App

Learn by Hands on Practice available in iamneo Portal

Unit III Activity : - Mind Map Diagram

 Draw a detailed Mind Map diagram to create a visual representation which illustrates the

different classes and methods within Java Collections Framework . Include key details such as

interfaces, classes and their respective implementations, along with methods commonly used

for each type which provides a comprehensive overview of how collections are organized and

utilized in Java programming.

14
8. Lecture Notes
Importance of Stream API in Java 8 and Beyond
The Stream API in Java, introduced in Java 8 within the java.util.stream package, is a powerful tool
that provides a functional approach for processing sequences of elements. It allows for high-level data
manipulation from various sources, such as collections and arrays.
 A stream pipeline is nothing but combined intermediate and terminal operations
 Many stream operations return a stream themselves. This allows operations to be chained to form a
larger pipeline. This enables certain optimizations, such as laziness and short-circuiting
Stream:
 A sequence of elements supporting sequential and parallel aggregate operations.
 Streams don’t store elements but pass elements from a source (like collections or arrays) through
a series of computational steps.
 A Stream does not retain its elements; it merely transports them from a source, such as a data
structure, array, or I/O channel, through a series of computational operations.
 Streams are inherently functional, meaning that operations performed on a stream do not alter the
original source. For instance, filtering a Stream derived from a collection results in a new Stream that
excludes the filtered elements, leaving the original collection unchanged. Additionally, Streams are
lazy, meaning they only execute code when necessary.
 Elements within a Stream are processed just once; to reprocess the same elements, a new Stream
must be created, similar to how an Iterator operates.
 IMPORTANCE OF STREAMS IN JAVA
 Enhanced Readability and Maintainability: The Stream API allows for more readable and
maintainable code by enabling a more declarative approach to processing collections. It uses method
chaining and functional programming constructs, which can make the code more concise and easier
to understand.
 Functional Programming: The Stream API introduces functional programming paradigms to Java,
allowing developers to use lambda expressions and functional interfaces. This leads to cleaner and
more efficient code, especially for tasks like filtering, mapping, and reducing collections.
 Parallel Processing: The Stream API provides built-in support for parallel processing. By simply
invoking the parallel() method, developers can leverage multi-core processors to perform operations
in parallel, which can significantly improve performance for large datasets.
 Lazy Evaluation: Streams are lazy by nature, meaning they do not compute elements until they
are needed. This can lead to performance optimizations as unnecessary calculations are avoided, and
resources are used more efficiently.
8. Lecture Notes

 Reduction in Boilerplate Code: Traditional iteration patterns, such as using loops, often require
boilerplate code. The Stream API reduces this boilerplate, allowing for more concise and expressive
code.
 Interoperability with Collections: The Stream API is seamlessly integrated with Java Collections
Framework. Methods like stream() and parallelStream() make it easy to create streams from existing
collections, enabling powerful and flexible operations on data.
 Rich Set of Operations: The Stream API provides a comprehensive set of operations, such as filter,
map, reduce, collect, flatMap, and many more. These operations cover a wide range of data
manipulation needs, making the API versatile and powerful.
he Stream API in Java is important because it enhances code readability and maintainability, introduces
functional programming, supports parallel processing, and provides a rich set of operations, all while
reducing boilerplate code and improving overall code quality.
CREATING STREAMS IN JAVA
From a Collection:
Using stream():
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();
From an Array:
String[] array = {"a", "b", "c"};
Stream<String> stream = Arrays.stream(array);
From a Builder:
Stream<String> stream = Stream.<String>builder()
.add("a")
.add("b")
.add("c")
.build();
From a Range (using IntStream or LongStream):
IntStream range = IntStream.range(1, 10); // 1 to 9
IntStream rangeClosed = IntStream.rangeClosed(1, 10); // 1 to 10
Using Stream.generate():
Stream<Double> randomNumbers = Stream.generate(Math::random).limit(10);
Using Stream.iterate():
Stream<Integer> evenNumbers = Stream.iterate(0, n -> n + 2).limit(10);
8. Lecture Notes
Most stream operations return a new stream, allowing them to be chained together to form a pipeline of
operations.
Stream operations in Java can be divided into two categories: Intermediate operations and Terminal
operations.
Operations that return a stream are known as intermediate operations. Examples include filter(),
distinct(), and sorted().
Operations that return a non-stream result are known as terminal operations. Examples include count(),
min(), and max().

Pipeline of Operations

A pipeline of operations consists of three components: a source, one or more intermediate operations,
and a terminal operation. Pipelines allow you to write database-like queries on a data source. In the
example below, an int array serves as the source, filter() and distinct() are intermediate operations, and
forEach() is a terminal operation.
IntStream.of(new int[] {4, 7, 1, 8, 3, 9, 7})
.filter((int i) -> i > 5)
.distinct()
.forEach(System.out::println);

Internal Iteration

Collections require explicit iteration, meaning you have to write the code to iterate over them. However,
all stream operations handle iteration internally for you. When using Java 8 Streams API, you don't need
to worry about iteration.

Parallel Execution

For performance gains when processing large amounts of data, parallel processing and multi-core
architectures are essential. Java 8 Streams can be processed in parallel without writing any multi-
threaded code. To process collections in parallel, simply use the parallelStream() method instead of the
stream() method.
8. Lecture Notes

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


names.add("David");
names.add("Johnson");
names.add("Samontika");
names.add("Brijesh");
names.add("John");

// Normal Execution
names.stream()
.filter((String name) -> name.length() > 5)
.skip(2)
.forEach(System.out::println);

// Parallel Execution
names.parallelStream()
.filter((String name) -> name.length() > 5)
.skip(2)
.forEach(System.out::println);

Single Traversal

Streams can be traversed only once, similar to iterators. Once a stream has been traversed, it is
considered consumed.

List<String> nameList = Arrays.asList("Dinesh", "Ross", "Kagiso", "Steyn");


Stream<String> stream = nameList.stream();
stream.forEach(System.out::println);
// This will cause an error: stream has already been operated upon or closed
stream.forEach(System.out::println);
8. Lecture Notes

The Stream interface in Java defines several methods that facilitate the manipulation of streams.
These methods can be categorized into two main types:

Intermediate Operations:

These operations transform the elements of a stream without terminating the stream itself. They
are typically followed by terminal operations that consume the stream. Here are some key
intermediate operations:

filter(Predicate p): Selects elements that match the given predicate p.


map(Function f): Transforms each element using the function f.
flatMap(Function f): Converts each element into a stream and then flattens these
streams into a single stream.
distinct(): Removes duplicate elements from the stream.
sorted(): Sorts elements in their natural order or using a custom comparator.
limit(long maxSize): Limits the number of elements in the stream to maxSize.
skip(long n): Skips the first n elements in the stream.
These operations allow developers to modify, filter, and prepare data within a stream according to
specific criteria or transformations before proceeding to further processing or collecting results.
8. Lecture Notes

Terminal Operations:

Terminal operations are operations that produce a final result or side-effect and terminate the
processing of a stream. Once a terminal operation is applied to a stream, the stream cannot be
used again. Some examples of terminal operations are:

forEach(): Performs a given action for each element of a stream.


toArray(): Collects the elements of a stream into an array.
reduce(): Combines the elements of a stream using a given function and returns a single result.
collect(): Collects the elements of a stream into a collection or other data structure.
count(): Counts the number of elements in a stream.
min(), max(): Returns the minimum or maximum element of a stream based on a given ordering.
8. Lecture Notes
METHODS OF STREAM INTERFACE

INTERMEDIATE OPERATIONS

Sl. No. Operation Method Signature


Description Example

1
Stream<T>
Filters elements based stream.filter(s ->
Filter filter(Predicate<?
on a condition s.length() > 1)
super T> predicate)

2
<R> Stream<R>
map(Function<? super Transforms elements stream.map(String::toUp
Map
T, ? extends R> using a function perCase)
mapper)

<R> Stream<R>
flatMap(Function<?
Flattens nested stream.flatMap(List::stre
FlatMap super T, ? extends
structures am)
Stream<? extends
R>> mapper)

Sorts elements in natural


4 Sorted Stream<T> sorted() stream.sorted()
order

5
Stream<T>
Sorts elements using a stream.sorted(Comparat
Sorted sorted(Comparator<?
comparator or.naturalOrder())
super T> comparator)

6 Removes duplicate
Distinct Stream<T> distinct() stream.distinct()
elements

21
8. Lecture Notes
METHODS OF STREAM INTERFACE

INTERMEDIATE OPERATIONS

Sl. No. Operation Method Signature


Description Example

7
Stream<T> limit(long Truncates the stream
Limit stream.limit(5)
maxSize) to a maximum size

8
Skips the first n
Skip Stream<T> skip(long n) stream.skip(3)
elements

22
8. Lecture Notes

map()
The map() method transforms each element of the stream into another form. For example,
converting a list of strings to a list of integers.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {


public static void main(String[] args) {
List<String> listOfStrings = Arrays.asList("1", "2", "3", "4", "5");

List<Integer> listOfIntegers = listOfStrings.stream()


.map(Integer::valueOf)
.collect(Collectors.toList());

System.out.println(listOfIntegers);
}
}
OUTPUT

[1, 2, 3, 4, 5]
8. Lecture Notes

filter()
The filter() method is used to exclude elements from a stream based on a condition. It takes
a Predicate that tests each element. If the Predicate returns true, the element is included;
otherwise, it is excluded.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Tester {


public static void main(String[] args){
List<String> lines = Arrays.asList("java", "c", "python");

List<String> result = lines.stream() // Convert list to stream


.filter(line -> !"c".equals(line)) // Exclude "c"
.collect(Collectors.toList()); // Collect the output to a List

result.forEach(System.out::println);
}
}
OUTPUT
javapython
8. Lecture Notes

flatMap()
method is used to flatten a structure of nested lists into a single list by first applying a
transformation and then flattening the result

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {


public static void main(String[] args) {
List<Integer> evens = Arrays.asList(2, 4, 6);
List<Integer> odds = Arrays.asList(3, 5, 7);
List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11);

List<Integer> numbers = Stream.of(evens, odds, primes)


.flatMap(list -> list.stream())
.collect(Collectors.toList());

System.out.println("flattened list: " + numbers);


}
}
OUTPUT
flattened list: [2, 4, 6, 3, 5, 7, 2, 3, 5, 7, 11]
8. Lecture Notes

distinct()

The distinct() method returns a stream with only unique elements, removing any duplicates.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> stringList = new ArrayList<>();
stringList.add("one");
stringList.add("two");
stringList.add("three");
stringList.add("one");

List<String> distinctStrings = stringList.stream()


.distinct()
.collect(Collectors.toList());

System.out.println(distinctStrings);
}
}
OUTPUT
[one, two, three]
8. Lecture Notes

sorted()

The sorted() method returns a stream with elements sorted according to natural order or a
provided comparator.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {


public static void main(String[] args) {
List<String> stringList = Arrays.asList("one", "three", "two");

List<String> sortedList = stringList.stream()


.sorted()
.collect(Collectors.toList());

System.out.println(sortedList);
}
}
[one, three, two]
8. Lecture Notes
METHODS OF STREAM INTERFACE

TERMINAL OPERATIONS

Sl. No. Operation Method Signature


Description Example

1 <R> R
collect(Collector<? Collects elements stream.collect(Collectors
Collect
super T, A, R> into a collection .toList())
collector)

3 Reduces elements
T reduce(T identity,
to a single value stream.reduce("",
Reduce BinaryOperator<T>
using an identity String::concat)
accumulator)
and accumulator

4
void
Performs an action stream.forEach(System.
ForEach forEach(Consumer<?
for each element out::println)
super T> action)

boolean Checks if any


stream.anyMatch(s ->
AnyMatch anyMatch(Predicate< elements match
s.length() > 1)
? super T> predicate) the given predicate

boolean Checks if all


stream.allMatch(s ->
6 AllMatch allMatch(Predicate<? elements match
s.length() > 1)
super T> predicate) the given predicate

7 boolean
Checks if no
noneMatch(Predicate stream.noneMatch(s ->
NoneMatch elements match
<? super T> s.length() > 1)
the given predicate
predicate)

8 Finds the first


Optional<T>
FindFirst element in the stream.findFirst()
findFirst()
stream

28
8. Lecture Notes
METHODS OF STREAM INTERFACE

TERMINAL OPERATIONS

Sl. No. Operation Method


Signature Description Example

9
Optional<T> Finds any element
FindAny stream.findAny()
findAny() in the stream

10
Counts the number
Count long count() stream.count()
of elements

11
IntSummaryS Returns statistics,
tatistics such as count,
SummaryStatistics stream.summaryStatistics()
summaryStati sum, min, average,
stics() and max

29
8. Lecture Notes

Terminal operations are the concluding actions taken on a stream, resulting in either a final output
or side effect. Unlike intermediate operations, which produce a new stream, terminal operations
are executed immediately and consume the elements of the stream. Once a terminal operation is
performed, the stream is exhausted and cannot be used again.

1. forEach:

Import java.util.Arrays;
mport java.util.List;
public class TerminalOperationsExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("JACK", "JOHN", “BOB");
names.stream()
.forEach(System.out::println);
}
}
OUTPUT
JACK
JOHN
BOB
8. Lecture Notes

2.Collect

The collect operation gathers the elements of a stream into a collection or a single result. It
requires a Collector as an argument, which defines the type of collection to be formed.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class TerminalOperationsExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = numbers.stream().filter(n -> n % 2==0).collect(Collectors.toList());
System.out.println("Even Numbers: " + evenNumbers);
}
}

OUTPUT
Even Numbers: [2, 4]
8. Lecture Notes

3.REDUCE

The reduce operation merges the elements of a stream into a single value. It uses a
BinaryOperator to define the reduction process.

import java.util.Arrays;
import java.util.List;
public class TerminalOperationsExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
System.out.println("Sum: " + sum);
}
}

OUTPUT
Sum:15
8. Lecture Notes

4. anyMatch and allMatch:

The anyMatch operation determines if any element in a stream meets a specified condition,
whereas the allMatch operation verifies if every element in the stream satisfies the given condition.

import java.util.Arrays;
import java.util.List;
public class TerminalOperationsExample {
public static void main(String[] args) {
// Create a list of integers
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Check if any element is greater than 3
boolean anyMatch = numbers.stream()
.anyMatch(n -> n > 3);
// Check if all elements are greater than 0
boolean allMatch = numbers.stream()
.allMatch(n -> n > 0);
// Print the result of anyMatch
System.out.println("Any Match: " + anyMatch);
// Print the result of allMatch
System.out.println("All Match: " + allMatch);
}
}

OUTPUT
Any Match: true
All Match: true
8. Lecture Notes
INTERMEDIATE STREAM METHODS (MAP, DISTINCT, SORTED, FILTER) TO FIND THE CUBE
OF ELEMENTS IN A LIST
import java.util.Arrays;
import java.util.List;
public class StreamIntermediateMethodsExample {
public static void main(String[] args) {
List<Integer> intList = Arrays.asList(5, 19, 8, 23, 6, 54, 32, 5, 23);
// Finding the cube of each element in the list
System.out.println("Cubes of elements:");
intList.stream()
.map(element -> element * element * element)
.forEach(element -> System.out.print(element + " "));
System.out.println();
// Applying distinct() to remove duplicates
System.out.println("\nOutput after distinct() implementation:");
intList.stream()
.distinct()
.map(element -> element * element * element)
.forEach(element -> System.out.print(element + " "));
System.out.println();
// Sorting the elements in natural order
System.out.println("\nOutput after sorted() implementation:");
intList.stream()
.distinct()
.sorted()
.map(element -> element * element * element)
.forEach(element -> System.out.print(element + " "));
System.out.println(); // Filtering elements less than 10000
System.out.println("\nOutput after filter() implementation:");
intList.stream()
.distinct()
.sorted()
.map(element -> element * element * element)
.filter(element -> element < 10000)
.forEach(element -> System.out.print(element + " "));
System.out.println(); } }
8. Lecture Notes

OUTPUT

Cubes of elements:
125 6859 512 12167 216 157464 32768 125 12167
Output after distinct() implementation:
125 6859 512 12167 216 157464 32768
Output after sorted() implementation:
125 216 512 6859 12167 32768 157464
Output after filter() implementation:
125 216 512 6859
8. Lecture Notes

METHODS OF STREAM INTERFACE

Sl. No. Creation operation Intermediate Terminal operation


operation

1 These functions create streams These are functions These are functions
operating on operating on streams to
streams resulting produce non-stream output
into output stream

2 Streams are created from These take stream These take stream element
various sources, namely: element as input as input
Collections,Array, Strings, Files
also primitive data types

3 These produce stream as These produce The result of functions


output stream as output performed if any are
returned.

4 There can be only one creation Any number of There can be only one
operation in stream pipeline (In intermediate terminal operation in
the beginning) operations chained stream pipeline (At the end)
to each other

5 eg: empty(), stream(), of, etc ex: filter, map, eg: forEach, collect,
flatmap, sorted, etc toArray, min, max, count,
etc
8. Lecture Notes
PROGRAM DEMONSTRATES VARIOUS STREAM OPERATIONS ON A LIST OF
EMPLOYEE OBJECTS

import java.util.*;
import java.util.stream.Collectors;
public class Main {
static class Employee {
private String firstName;
private int age;
private String departmentName;
private String city;
private int rank;
private String gender;
public Employee(String firstName, int age, String departmentName, String city, int rank,
String gender) {
this.firstName = firstName;
this.age = age;
this.departmentName = departmentName;
this.city = city;
this.rank = rank;
this.gender = gender; }
public String getFirstName() { return firstName; }
public int getAge() { return age; }
public String getDepartmentName() { return departmentName; }
public String getCity() { return city; }
public int getRank() { return rank; }
public String getGender() { return gender; }
8. Lecture Notes
@Override
public String toString() {
return "Employee{" +
"firstName='" + firstName + '\'' +
", age=" + age +
", departmentName='" + departmentName + '\'' +
", city='" + city + '\'' +
", rank=" + rank +
", gender='" + gender + '\'' +
'}';
}
}
public static void main(String[] args) {
List<Employee> list = Arrays.asList(
new Employee("Alice", 25, "HR", "Delhi", 1, "Female"),
new Employee("Bob", 30, "IT", "Mumbai", 2, "Male"),
new Employee("Anita", 22, "Finance", "Delhi", 3, "Female"),
new Employee("Alex", 35, "IT", "Delhi", 60, "Male"),
new Employee("David", 28, "HR", "Mumbai", 55, "Male"),
new Employee("Eva", 27, "Finance", "Delhi", 70, "Female")
// Add more Employee objects as needed
);

// 1. List of employees whose first name starts with alphabet A


List<Employee> lstEmpName = list.stream()
.filter(emp -> emp.getFirstName().startsWith("A"))
.collect(Collectors.toList());

System.out.println("List of employees whose name starts with letter A : " + lstEmpName);


// 2. Group the employees by department names
Map<String, List<Employee>> mapData = list.stream()
.collect(Collectors.groupingBy(Employee::getDepartmentName));
System.out.println("Employees grouped by the department names : " + mapData);
8. Lecture Notes
// 3. Find the total count of employees using stream
long countEmployee = list.stream().count();
System.out.println("Total count of employees : " + countEmployee);

// 4. Find the max age of employee


OptionalInt maxAge = list.stream().mapToInt(Employee::getAge).max();
System.out.println("Max age of employee : " + maxAge.getAsInt());

// 5. Find all departments names


List<String> lstDepartments = list.stream()
.map(Employee::getDepartmentName).distinct()
.collect(Collectors.toList());
System.out.println("All distinct department names : " + lstDepartments);

// 6. Find the count of employees in each department


Map<String, Long> countEmployeeInEachDept = list.stream()
.collect(Collectors.groupingBy(Employee::getDepartmentName, Collectors.counting()));
System.out.println("Employee count in each department : " + countEmployeeInEachDept);

// 7. Find the list of employees whose age is less than 30


List<Employee> lstEmployee = list.stream()
.filter(emp -> emp.getAge() < 30).collect(Collectors.toList());
System.out.println("List of employees whose age is less than 30 : " + lstEmployee);

// 8. Find the list of employees whose rank is between 50 and 100


List<Employee> lstEmp = list.stream()
.filter(emp -> emp.getRank() > 50 && emp.getRank() < 100)
.collect(Collectors.toList());
System.out.println("List of employees whose rank is between 50 and 100 : " + lstEmp);

// 9. Find the average age of male and female employees


Map<String, Double> mapAvgAge = list.stream()
.collect(Collectors.groupingBy(Employee::getGender,
Collectors.averagingInt(Employee::getAge)));
8. Lecture Notes
System.out.println("Average age of male and female employees : " + mapAvgAge);
// 10. Find the department having maximum number of employees
Map.Entry<String, Long> entry = list.stream()
.collect(Collectors.groupingBy(Employee::getDepartmentName,
Collectors.counting())).entrySet().stream()
.max(Map.Entry.comparingByValue()).get();
System.out.println("Department having maximum number of employees : " + entry);

// 11. Find the employees who stay in Delhi and sort them by their names
List<Employee> lstDelhiEmployee = list.stream()
.filter(emp -> emp.getCity().equals("Delhi"))
.sorted(Comparator.comparing(Employee::getFirstName)).collect(Collectors.toList());
System.out.println("List of employees who stay in Delhi and sort them by their names : " +
lstDelhiEmployee);

// 12. Find the average rank in all departments


Map<String, Double> collect = list.stream()
.collect(Collectors.groupingBy(Employee::getDepartmentName,
Collectors.averagingInt(Employee::getRank)));
System.out.println("Average rank in all departments : " + collect);

// 13. Find the highest rank in each department


Map<String, Optional<Employee>> employeeData = list.stream()
.collect(Collectors.groupingBy(Employee::getDepartmentName,
Collectors.minBy(Comparator.comparing(Employee::getRank))));
System.out.println("Highest rank in each department : " + employeeData);
// 14. Find the list of employees and sort them by their rank
List<Employee> empRankSorted = list.stream()
.sorted(Comparator.comparing(Employee::getRank)).collect(Collectors.toList());
System.out.println("List of employees sorted by their rank : " + empRankSorted);
// 15. Find the employee who has the second highest rank
Employee employee = list.stream()
.sorted(Comparator.comparing(Employee::getRank)).skip(1).findFirst().get();
System.out.println("Second highest rank employee : " + employee);
}
}
8. Lecture Notes

PROGRAM THAT TAKES A LIST OF INTEGERS AND PRINTS OUT ONLY THE EVEN NUMBERS

import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> intList = List.of(15, 20, 48, 63, 49, 27, 56, 32, 9);
printEvenNumbers(intList);
}

private static void printEvenNumbers(List<Integer> intList) {


System.out.print("\nEven numbers are: ");
intList.stream()
.filter(element -> (element % 2 == 0))
.forEach(element -> System.out.print(element + " "));
}
}

OUTPUT

Even numbers are: 20 48 56 32


8. Lecture Notes
WRITE A PROGRAM THAT PERFORMS STREAM OPERATIONS LIKE FILTERING, MAPPING, AND
REDUCING

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class StreamOperationsExample {


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

// Filtering even numbers


List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.toList();
System.out.println("Even numbers: " + evenNumbers);

// Mapping to squares
List<Integer> squares = numbers.stream()
.map(n -> n * n)
.toList();
System.out.println("Squares: " + squares);

// Reducing to sum of all numbers


int sum = numbers.stream()
.reduce(0, Integer::sum);
System.out.println("Sum of all numbers: " + sum);
}
}
8. Lecture Notes
CREATE AN INFINITE STREAM GENERATOR THAT GENERATES PRIME NUMBERS. IMPLEMENT
METHODS TO CHECK FOR PRIMALITY AND GENERATE THE NEXT PRIME NUMBER.

import java.util.stream.Stream;
import java.util.stream.IntStream;

public class PrimeNumberGenerator {


public static void main(String[] args) {
// Generate an infinite stream of prime numbers
Stream<Integer> primeStream = Stream.iterate(2, PrimeNumberGenerator::nextPrime);

// Print the first 20 prime numbers


primeStream.limit(20).forEach(System.out::println);
}

// Method to check if a number is prime


private static boolean isPrime(int number) {
if (number < 2) {
return false;
}
return IntStream.rangeClosed(2, (int) Math.sqrt(number))
.allMatch(n -> number % n != 0);
}

// Method to find the next prime number after a given number


private static int nextPrime(int after) {
int number = after + 1;
while (!isPrime(number)) {
number++;
}
return number;
}
}
8. Lecture Notes
WRITE A PROGRAM THAT READS A TEXT FILE CONTAINING SENTENCES. TOKENIZE
EACH SENTENCE INTO WORDS, FILTER OUT STOPWORDS, AND PRINT THE REMAINING
WORDS.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class TextFileProcessor {
private static final Set<String> STOPWORDS = Set.of(
"a", "an", "the", "and", "or", "but", "if", "is", "are", "was", "were", "in", "of", "to", "with", "on"
);
public static void main(String[] args) {
String filePath = "path/to/text/file.txt"; // Replace with your file path
try {
List<String> lines = Files.readAllLines(Paths.get(filePath));
lines.stream()
.flatMap(line -> Arrays.stream(line.split("\\W+"))) // Tokenize into words
.filter(word -> !STOPWORDS.contains(word.toLowerCase()) && !word.isEmpty()) //
Filter out stopwords and empty words
.forEach(System.out::println); // Print remaining words
} catch (IOException e) {
e.printStackTrace();
}
}
}
8. Lecture Notes

STREAM AND JOIN EXAMPLE

import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;

public class StreamAndJoinExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter words separated by spaces: ");
String input = scanner.nextLine().trim();
if (input.isEmpty()) {
System.out.println("No input provided.");
return;
}
String[] words = input.split("\\s+");
// Using Streams to join the words with a hyphen
String joinedWords = Arrays.stream(words)
.collect(Collectors.joining("-"));
System.out.println("Joined words with hyphen: " + joinedWords);
}
}

OUTPUT

Enter words separated by spaces: apple banana orange grape


Joined words with hyphen: apple-banana-orange-grape
9. Assignment - I

IMPORTANCE OF STREAM API

Write a Java program to demonstrate the efficiency of the Stream API over traditional
loops for processing large collections. Create a list of 1,000,000 random integers and
compare the time taken to filter out even numbers using a traditional for loop versus
using the Stream API.

Implement a functional-style program using the Stream API to process a list of student
records. Each record contains the student's name, age, and score. Filter students with
scores greater than 70, sort them by name, and collect the result into a new list. Print
the filtered and sorted list.

46
9. Assignment - II

MAPPING (MAP, FLATMAP)

Write a Java program that takes a list of sentences and uses the Stream API to split
each sentence into words, then flattens the resulting lists of words into a single stream
of words. Print all the words.

Write a Java program that uses the Stream API to skip the first 2 elements of a list of integers
and then limit the result to the next 3 elements. Print the resulting list.

47
9. Assignment - III

Data Analysis and Reporting Implementation:

Develop a Java program that processes a collection of sales transactions, categorizes transactions by
product type using streams, calculates the total sales revenue for each product category, and generates a
report summarizing the results. Utilize stream operations such as mapping and reducing to efficiently
aggregate sales data and showcase the practical application of streams in data analysis tasks.

48
9. Assignment - IV

Stream Processing Workflow

Implementation: Implement a Java program that reads a list of employee objects, filters out
employees earning less than a specified salary threshold, computes the average salary of the
remaining employees using streams, and prints the result. Ensure the program demonstrates
how streams enhance code readability and maintainability in handling data filtering and
aggregation tasks.

49
9. Assignment - V

Integration of Stream Operations in Real-World Applications

Explore how stream operations such as mapping, reducing, and filtering are integrated into
real-world applications for data analysis and reporting. Provide an example scenario where
streams are used to process sales transactions, categorize products by type, calculate total
sales revenue for each category, and generate a comprehensive report. Discuss the
advantages of using streams for data aggregation and reporting tasks, emphasizing code
simplicity and readability.

50
10. Part A Questions & Answers

1. What is the Stream API in Java?(K1,CO3)


The Stream API in Java is a powerful feature introduced in Java 8 that allows for
processing sequences of elements, such as collections, in a functional style. It provides a way to
perform bulk operations on data with the ability to filter, map, and reduce elements.

2. How does the Stream API improve performance?( K2,CO3)


The Stream API can improve performance by enabling parallel execution of
operations. This is achieved using the parallelStream() method, which divides the tasks into
smaller chunks that can be processed concurrently, leveraging multi-core processors.

3. Why is the Stream API considered a significant addition to Java 8? ?( K2,CO3)

The Stream API is significant because it introduces functional programming


concepts to Java, enabling more readable and concise code for bulk data operations. It helps in
writing more declarative code, which is easier to understand and maintain.

4. What are the benefits of using the Stream API over traditional loops? ?( K2,CO3)

The benefits of using the Stream API over traditional loops include improved code
readability, ease of parallel processing, and the ability to write more concise and expressive code
using method references and lambda expressions.

5. Write a program to create a stream from a list of integers and print each element.
?( K2,CO3)
import 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);
numbers.stream().forEach(System.out::println);
}
}
10. Part A Questions & Answers

6. Define a functional interface. ?( K2,CO3)


A functional interface is an interface that contains exactly one abstract method. It can be used as
the assignment target for a lambda expression or method reference. An example is the
java.util.function.Predicate interface.
7. How do you create a stream from a collection in Java? ?( K2,CO3)
You can create a stream from a collection in Java using the stream() method. For example,
List<String> list = new ArrayList<>(); Stream<String> stream = list.stream();.
8. Can streams be created from arrays? If yes, how? ?( K3,CO3)
Yes, streams can be created from arrays using the Arrays.stream() method. For example, String[]
array = {"a", "b", "c"}; Stream<String> stream = Arrays.stream(array);.
9. What does the map method do in a stream? ?( K3,CO2)
The map method in a stream applies a given function to each element of the stream and returns
a new stream with the transformed elements.
10. Describe the filter method in streams. ?( K1,CO3)
The filter method in streams is used to select elements based on a given predicate. It returns a
new stream containing only the elements that match the predicate.
11. What is the purpose of the distinct method in a stream? ?( K2,CO3)
The distinct method in a stream returns a new stream that contains only the unique elements,
removing duplicates based on the equals method.
12. Write a program to filter out even numbers from a list and print them. ?( K3,CO3)
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FilterEvenNumbers {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
evenNumbers.forEach(System.out::println);
}
}
52
10. Part A Questions & Answers
13. What does the collect method do in streams? ?( K1,CO3)
The collect method in streams is a terminal operation that transforms the elements of the stream into
a different form, typically a collection like a list, set, or map.
How does the reduce method work in a stream?
The reduce method in a stream performs a reduction on the elements using an associative
accumulation function and returns an Optional with the reduced value.

14. Write a program to convert a list of strings to uppercase and print them. ?( K3,CO3)
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ConvertToUpperCase {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry");
List<String> upperCaseWords = words.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
upperCaseWords.forEach(System.out::println);
}
}

15. Write a program to check if any number in a list is greater than 50. ?( K3,CO3)
import java.util.Arrays;
import java.util.List;

public class AnyMatchExample {


public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50, 60, 70);
boolean anyGreaterThan50 = numbers.stream().anyMatch(n -> n > 50);
System.out.println("Any number greater than 50: " + anyGreaterThan50);
}
}
11. Part B Questions
1. Explain the key principles of functional programming supported by the Stream API in Java.
Discuss immutability, higher-order functions, and lazy evaluation in the context of streams.
Provide examples demonstrating how these concepts are applied when working with streams.
(K2,CO3)
2. Compare different ways to create streams in Java, including from collections, arrays, and using
Stream.of(). Discuss scenarios where each approach is suitable and the advantages of using
streams for data processing tasks.(K2,CO3)
3. Describe the methods defined in the Stream interface in Java. Explain the role of methods such
as filter, map, flatMap, sorted, distinct, limit, and skip in stream processing. Provide examples
illustrating the usage of each method and discuss their impact on stream behavior. (K2,CO3)
4. Discuss the purpose of terminal operations such as collect and reduce in stream processing.
Compare and contrast these operations with respect to their ability to aggregate stream
elements into collections or single values. Provide examples demonstrating their usage in
practical scenarios. (K2,CO3)
5. Explain how the forEach method is used to iterate over elements in a stream. Discuss scenarios
where forEach is preferable over traditional iteration approaches. Describe the role of matching
operations (anyMatch, allMatch, noneMatch, findFirst, findAny) in stream-based searching and
retrieval tasks. Provide examples showcasing their usage and efficiency. (K2,CO3)
6. Describe the purpose of counting operations (count) and summarizing operations
(summaryStatistics) in stream processing. Explain how these operations provide insights into
the size, distribution, and characteristics of data sets. Provide examples demonstrating their
application in data analysis and reporting tasks. (K23CO3)
7. Write a Java program that reads a list of integers, filters out the odd numbers, squares each
even number, and prints the squared values. Use streams and demonstrate the use of filter,
map, and forEach methods. (K2,CO3)
8. Develop a Java program that reads a list of strings, removes duplicates, counts the
occurrences of each distinct string, and prints the results. Use streams and demonstrate the
use of distinct, collect, and groupingBy collectors. (K2,CO3)
9. Create a Java program that processes a collection of employee objects containing name,
department, and salary fields. Compute the total salary expenses for each department, find
the department with the highest average salary, and print the results. Use streams and
demonstrate the use of groupingBy, summingDouble, maxBy, and collectingAndThen
collectors.(K3,CO3)

54
12. Supportive Online Certifications

1. Java Programming: Complete Beginner to Advanced https://www.udemy.com/course/java-


programming-complete-beginner-to- advanced/(Paid)

2. Java DeveloperCertification (Infosys Springboard):


https://infyspringboard.onwingspan.com/web/en/app/toc/lex_auth_01319338454
0020736264_shared/overview

3. Java Programming Masterclass updated to Java 17: https://www.udemy.com/course/java-


the-complete-java-developer-course/ (Paid)

4. Programming in Java: https://nptel.ac.in/courses/106/105/106105191/ (Paid)

5. Java Learning Subscription: https://education.oracle.com/java-se-8-


fundamentals/courP_3348 (Paid)

55
13. Real Time Applications

 Desktop GUI Programs

 Mobile Applications

 Artificial intelligence

 Web based Applications

 Big data technology

 Gaming Applications

 Business Applications

 Embedded Systems

 Cloud based Applications

 Scientific Applications

 Distributed Applications

 Web servers and Application servers

 Software Tools

56
14. Contents Beyond the Syllabus
Custom Collectors
Java’s Collectors class provides a wide range of predefined collectors, but sometimes custom
collectors are necessary to perform complex reductions.
Creating a Custom Collector
A custom collector can be created by implementing the Collector interface or using the Collector.of
method.
Collector<Employee, StringJoiner, String> employeeNameCollector = Collector.of(
() -> new StringJoiner(", "), // Supplier
(j, e) -> j.add(e.getFirstName()), // Accumulator
StringJoiner::merge, // Combiner
StringJoiner::toString // Finisher
);
String names = employees.stream().collect(employeeNameCollector);
System.out.println("Employee names: " + names);
Using Stream APIs in concurrent environments involves leveraging Java's Stream API to process
data in parallel, allowing for improved performance on multi-core processors. This approach is
particularly useful for large datasets or computationally intensive tasks where parallel execution can
significantly reduce processing time.
Parallel Streams in Java
Java's Stream API supports parallel processing through the use of parallel streams. Parallel streams
divide the data into multiple chunks and process each chunk concurrently on separate threads,
utilizing the available CPU cores effectively.
Creating Parallel Streams
You can create a parallel stream from any existing stream by invoking the parallel() method. For
instance:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// Sequential stream
numbers.stream().forEach(System.out::println);
// Parallel stream
numbers.parallelStream().forEach(System.out::println);

57
14. Contents Beyond the Syllabus
Parallelism and Performance Considerations
Automatic Parallelism: Java manages the parallelism internally, deciding the optimal number of threads
based on the available processors. You can control this behavior using system properties or
programmatically.
Thread Safety: Operations performed within a parallel stream should be thread-safe. This includes any
shared mutable state or resources accessed within the stream operations.
Ordering: Parallel streams do not guarantee the order of processing, which can differ from sequential
streams. If maintaining order is important, use forEachOrdered() instead of forEach().
Example: Processing Employees in Parallel
Let's consider an example where we have a list of employees and want to compute the total salary
using parallel streams:
class Employee {
private String name;
private double salary;

// Constructor, getters, and setters


}
List<Employee> employees = Arrays.asList(
new Employee("Alice", 50000),
new Employee("Bob", 60000),
new Employee("Charlie", 70000),
new Employee("David", 55000)
);
// Sequential stream to calculate total salary
double totalSalarySequential = employees.stream()
.mapToDouble(Employee::getSalary)
.sum();
// Parallel stream to calculate total salary
double totalSalaryParallel = employees.parallelStream()
.mapToDouble(Employee::getSalary)
.sum();
System.out.println("Total salary (Sequential): " + totalSalarySequential);
System.out.println("Total salary (Parallel): " + totalSalaryParallel);
58
14. Contents Beyond the Syllabus

Best Practices for Using Parallel Streams

To effectively use parallel streams in concurrent environments, consider the following best
practices:
Ensure Thread Safety: Operations performed within stream operations, such as mapping or
filtering, should be thread-safe to avoid data corruption or inconsistency.

Avoid Stateful Operations: Minimize the use of stateful operations or mutable shared state
within stream operations. Prefer immutable data structures or safe concurrent collections.

Benchmarking and Optimization: Measure the performance gain from using parallel streams
against sequential streams. Optimize the parallelism settings based on benchmark results and
hardware characteristics.

Control Parallelism: Use ForkJoinPool or system properties


(java.util.concurrent.ForkJoinPool.common.parallelism) to control the level of parallelism if
needed.

Keep Stream Operations Stateless: Stream operations should ideally be stateless or operate on
immutable data to facilitate parallel execution without side effects.

59
15. Assessment Schedule
Tentative schedule for the Assessment During 2024-2025 Odd Semester

S. Name of the
Assessment Start Date End Date Portion
No.

As Per Academic As Per Academic


1 Unit Test 1 Unit 1
Schedule Schedule

As Per Academic As Per Academic


2 FIAT Unit 1 & 2
Schedule Schedule
As Per Academic As Per Academic
3 Unit Test 2 Unit 3
Schedule Schedule
As Per Academic As Per Academic
4 SIAT Unit 3 & 4
Schedule Schedule
As Per Academic As Per Academic
5 Revision 1 Unit 5, 1 & 2
Schedule Schedule
As Per Academic As Per Academic
6 Revision 2 Unit 3 & 4
Schedule Schedule
As Per Academic As Per Academic
7 Model All 5 Units
Schedule Schedule

60
16. Prescribed Text Books
&
Reference Books
TEXT BOOK:
1. Cay S. Horstmann, "Core Java Volume I--Fundamentals,"
12th Edition, 2019.
2. Joshua Bloch, "Effective Java," 3rd Edition, 2018.
3. Raoul-Gabriel Urma, "Java 8 in Action: Lambdas, Streams,
and Functional-Style Programming," 1st Edition, 2014.
4. Herbert Schildt, "Java: The Complete Reference," 11th
Edition, 2018.
5. Alan Mycroft and Martin Odersky, "Programming in Scala,"
4th Edition, 2020.
REFERENCES:
1. Bruce Eckel, "Thinking in Java," 4th Edition, 2006.
2. Herbert Schildt, "Java: A Beginner's Guide," 8th Edition,
2019.
3. Richard Warburton, "Java 8 Lambdas: Pragmatic Functional
Programming," 1st Edition, 2014.

61
17. Mini Project - I

Inventory Management System:

Description: Implement a system to manage inventory items with attributes such as name,
category, quantity, and price. Use streams to perform operations like sorting items by category,
calculating total inventory value, finding items with low stock (quantity below a threshold), and
generating alerts.

Key Concepts: Sorting, filtering, mapping inventory items, reducing operations, and
handling data aggregation and reporting.

4 62
17. Mini Project - II

Social Media Analytics:

Description: Create a program that processes social media posts or comments. Use streams
to analyze post data, such as counting the occurrences of specific keywords, identifying
trending topics, calculating engagement metrics (likes, shares, comments), and generating
analytics reports.

Key Concepts: Filtering based on text content, mapping post attributes, counting
occurrences, and summarizing analytics using collectors.

4 63
17. Mini Project - III
Collect Unique Symbols From Set of Cards

Library Book Management:

Description: Create a system to manage a library's book inventory. Each book has attributes
like title, author, genre, quantity, and price. Use streams to sort books by genre, calculate the
total value of the library's inventory, find books with low stock (quantity below a threshold), and
generate alerts for books needing replenishment.

Key Concepts: Sorting books by genre, filtering based on quantity, calculating inventory
value, and generating alerts for low stock items.

Online Store Product Analysis:

Description: Develop a program to analyze products sold in an online store. Products have
attributes such as name, category, sales quantity, price, and customer ratings. Use streams to
group products by category, compute total sales revenue for each category, find top-rated
products, and generate a sales performance report.

Key Concepts: Grouping products, aggregating sales revenue, filtering top-rated products,
and generating detailed sales reports.

4 64
17. Mini Project - IV

Financial Portfolio Management:

Description: Develop a system to manage a financial portfolio containing investments like


stocks, bonds, and mutual funds. Each investment has attributes such as name, type, quantity,
price, and market value. Use streams to categorize investments by type, calculate total
portfolio value, find investments with low performance, and generate investment performance
reports.

Key Concepts: Categorizing investments, calculating portfolio value, analyzing investment


performance, and generating detailed reports for portfolio management.

4 65
17. Mini Project - V

Restaurant Menu Management:

Description: Implement a system for managing a restaurant's menu items. Each menu item
includes attributes like name, category (appetizer, main course, dessert), price, and
availability. Use streams to categorize menu items, calculate total revenue, find items priced
within a specified range, and generate daily sales summaries.
Key Concepts: Categorizing menu items, filtering by price range, aggregating revenue, and
summarizing daily sales activities.

Healthcare Patient Records Analysis:

Description: Build an application for analyzing patient records in a healthcare setting.


Patient records contain attributes like name, age, medical condition, treatment history, and
medication prescriptions. Use streams to filter patients by medical condition, calculate average
patient age, identify high-risk patients based on conditions, and generate health reports.
Key Concepts: Filtering patient records, calculating average age, identifying high-risk
patients, and generating comprehensive health reports.

4 66
Thank you

Disclaimer:

This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document through
email in error, please notify the system manager. This document contains
proprietary information and is intended only to the respective group / learning
community as intended. If you are not the addressee you should not disseminate,
distribute, or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system.
If you are not the intended recipient you are notified that disclosing, copying,
distributing, or taking any action in reliance on the contents of this information is strictly
prohibited.

90

You might also like