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

Unit -3 22cs305- Advanced Java Programming-unit3

This document outlines the course structure for 'Advanced Java Programming' at RMK Group of Educational Institutions, including objectives, syllabus, prerequisites, and course outcomes. It details various units covering topics such as the Java Collections Framework, I/O operations, Stream API, and advanced string processing. Additionally, it includes a lecture plan, assessment schedule, and recommended textbooks and references.

Uploaded by

PRABHU G
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit -3 22cs305- Advanced Java Programming-unit3

This document outlines the course structure for 'Advanced Java Programming' at RMK Group of Educational Institutions, including objectives, syllabus, prerequisites, and course outcomes. It details various units covering topics such as the Java Collections Framework, I/O operations, Stream API, and advanced string processing. Additionally, it includes a lecture plan, assessment schedule, and recommended textbooks and references.

Uploaded by

PRABHU G
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 69

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
Departmen : CSE/IT/ADS/CSD/ECE/
t BatchIntegrated)
/ ACT/VLSI
Year : 2023 – 2027 / II
Created by : All Subject Handling
Date Staff Members
: 29.06.2024

4
Table of
Contents
Pag
Sl.No. Topic
e
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 LT
INTEGRATED)
P
UNIT I COLLECTIONS FRAMEWORK AND UTILITY CLASSES 9+6
Introduction to Collections Framework - Collection Interface- Methods
C in
Collection 3
Interface - - Iterable and Iterator Interfaces - List Interface- ArrayList -
0
LinkedList - Set Interface - HashSet- LinkedHashSet - TreeSet - Map
Interface - HashMap - LinkedHashMap- TreeMap - Queue 2Interface -
PriorityQueue - Deque Interface - Utility Classes. 4
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 9+6
HANDLING
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
7
through it using random access, insert, delete, and modify text at specific
positions within the file.
UNIT III STREAM API AND FUNCTIONAL 9+6
PROGRAMMING 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 9+6
SERIALIZATION, 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 9+6
EXPRESSIONS
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.
9
2. Herbert Schildt, "Java: A Beginner's Guide," 8th Edition, 2019.
3. Richard Warburton, "Java 8 Lambdas: Pragmatic
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


CO1 structure 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
CO3 applying K3

functional programming techniques..

CO4 Understand and implement advanced object serialization K3


techniques.

CO5 Effectively use regular expressions for advanced text processing K3


tasks.

CO6 Build simple applications using advanced java programming K3


concepts.

1
1
5. CO-PO
Mapping

Program
Program Outcomes Status
Course
Outcome Outcomes

s P PO PO PO PO PO PO PO PO PO PO PO PS PS PS
O O O O
2 3 4 5 6 7 8 9 10 11 12
1 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

1
2
6. LECTURE
Sl.
N
Topics
PLAN
No. Propos Actual Pertaini
Taxon
o my Mode
of. ed Date ng Level of
o
Period Date CO Deliver
.
s y
As per
Overview of
Time As per
Stream API -
table & Time
Importance of
Academ table &
Stream API in MD 1,
ic Academic
1 Java 8 and 1 CO3, CO6 K3 MD 4
Calenda Calendar
Beyond
r
As per As per
Functional Time Time
Programming table & table
Concepts - Academ & MD 1,
2 1 ic CO3,CO6 K3
Creating Streams Academic MD 4
Calenda Calendar
r
As per
Stream Interface As per
Time
Methods - Stream Time
table &
Operations - table &
Academ MD 1,
3 Intermediate 1 Academic CO3, CO6 K3
ic MD 4
Filtering (filter) Calendar
Calenda
r
As per
Mapping (map, As per
Time
flatMap)-Sorting table & Time
(sorted)-Distinct Academ table & MD 1,
4 (distinct) 1 ic Academic CO1, CO6 K3
MD 4
Calenda Calendar
r
Limit and Skip As per
(limit, skip) - As per
Time
Terminal table & Time
Operations - Academ table & MD 1,
5,6 Collecting Results 2 ic Academic CO1, CO6 K3
(collect) MD 4
Calenda Calendar
r
As per
As per
Reducing and Time
Summarizing table & Time
(reduce, Academ table & MD 1,
7 summaryStatistic 1 ic Academic CO1, CO6 K3
MD 4
s) Calenda Calendar
r
Iterating
(forEach) - As per
Matching and As per
Time
* MD1 – Oral Presentation
Finding Time
table & 1
* MD 4 – Hands on using any Java
(anyMatch, table &
Academ MD 1, 3
7. Activity Based
Learning
Common
Activities

Learning Methods Activities

Class Exercises, Challenge


Learn by Solving Problems Yourself, 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 : Stream Processing Pipeline

⮚ Challenge Objective:
Students will design and implement a data processing pipeline using the Stream
API and functional programming concepts. The focus will be on understanding
how to compose multiple stream operations to achieve a complex task, similar
to how real-world data pipelines work.
Setup:
1. Divide students into small teams (3-4 members each).
2. Provide each team with a dataset. This could be a CSV file containing
information like customer transactions, student grades, social media posts, etc.
Ensure that the dataset is rich enough to allow for multiple processing
operations.
3. Challenge teams to implement a series of transformations and analyses on
the data using the Stream API.

1
4
7. Activity Based
⮚Steps:
Learning
1. Initial Analysis:
Each team starts by analyzing the dataset and identifying potential stream
operations that could be applied. For example, filtering out invalid entries,
mapping values to a different format, sorting, grouping, etc.
Deliverable: Each team submits a plan outlining the sequence of stream
operations they intend to use.
2. Pipeline Implementation:
Teams implement their planned processing pipeline in Java using the Stream API.
The pipeline should include operations like filter, map, reduce, collect,
groupingBy, and possibly custom operations.
Deliverable: A working Java program that processes the dataset as described in
the plan.
3. Testing and Refinement:
Teams test their pipeline with different inputs and edge cases to ensure
robustness.
Deliverable: Teams refine their pipeline based on the results of their tests.
4. Benchmarking:
Introduce a large dataset to test the performance of the pipelines.
Teams should try to optimize their pipeline, possibly by using parallel streams.
Deliverable: Performance metrics for both sequential and parallel processing.
5. Presentation and Discussion:
Each team presents their pipeline design, implementation, and results to the
class. They explain their choice of operations, any challenges they encountered,
and how they optimized their code.
Deliverable: A brief presentation (with code and output) followed by a Q&A
session where other teams can ask questions or suggest improvements.
6. Collaborative Enhancement:
After the presentations, mix up the teams and have them work together to
integrate the best ideas from each team's pipeline into a single, optimized
pipeline.
Deliverable: A final, optimized pipeline that the entire class contributed to.

1
4
8. Lecture Notes
Overview of Stream API
A stream, in Java, is a sequence of elements that can be processed in parallel or
sequentially. It represents a pipeline of operations that can be performed on a data
source, such as a collection, array, or I/O channel.
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 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.
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.
8. Lecture Notes
❑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.
❑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.
The 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.

❑ Functional Programming Concepts

Functional programming in Java, especially through the Stream API, emphasizes writing
code in a declarative style, focusing on what to do rather than how to do it.
Key concepts include:

Immutability: Streams process data without modifying the original source, encouraging
immutability.
Pure Functions: Functions used in streams (like map, filter) should avoid side effects,
ensuring the same output for the same input.
Higher-Order Functions: Streams use functions like filter, map, and reduce, which
take other functions as arguments, enabling powerful data transformations.
Lazy Evaluation: Streams are lazily evaluated, meaning operations are not executed
until a terminal operation (like collect) is invoked.
Chaining: Stream operations can be chained together to create a pipeline, where data
flows through multiple transformations in a single, readable statement.
Concurrency: The Stream API supports parallel processing, making it easier to write
concurrent programs using parallelStream.
8. Lecture Notes
❑ Creating Streams
Streams can be created from various sources in Java, such as collections, arrays, or I/O
channels. The java.util.stream.Stream class provides several methods to create streams.
For instance, the stream() method can be called on collections to obtain a sequential
stream that processes elements in a defined order. Conversely, the parallelStream()
method returns a parallel stream that allows for concurrent processing of elements,
taking advantage of multi-core processors.

Additionally, the Stream.of() method allows creating streams from individual elements or
arrays. It provides a convenient way to create a stream with a fixed set of elements.
Moreover, streams can be generated using the Stream.generate() or Stream.iterate()
methods, which generate an infinite stream based on a supplier or an iterative function,
respectively.
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
❑ Stream Interface Methods & Stream Operations

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
Terminal Operations:
Notes
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
INTERMEDIATE OPERATIONS

Sl. No. Operatio Method Signature


n Description Example

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

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

<R> Stream<R>
flatMap(Function<?
FlatMa Flattens nested stream.flatMap(List::s
super T, ? extends
p structures tream)
Stream<? extends
R>> mapper)

4 Sorts elements in
Sorted Stream<T> sorted() stream.sorted()
natural order

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

6 Distinc Stream<T> Removes duplicate


stream.distinct()
t distinct() elements

23
8. Lecture
Notes
METHODS OF STREAM INTERFACE

INTERMEDIATE OPERATIONS

Sl. No. Operatio Method Signature


n Description Example

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

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

24
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
Collects
collect(Collector<? stream.collect(Collect
Collect elements into a
super T, A, R> ors.toList())
collection
collector)

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

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

boolean Checks if any


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

boolean Checks if all


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

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

8 Finds the first


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

30
8. Lecture
Notes
METHODS OF STREAM INTERFACE

TERMINAL OPERATIONS

Sl. No. Operation Method


Signature Description Example

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

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

11
Returns
IntSummary
statistics, such
Statistics stream.summaryStatisti
SummaryStatistics as count, sum,
summarySt cs()
min, average,
atistics()
and max

31
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 These are These are functions


streams functions operating on streams to
operating on produce non-stream
streams resulting output
into output stream

2 Streams are created from These take stream These take stream
various sources, namely: element as input element 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 Any number of There can be only one
creation operation in stream intermediate terminal operation in
pipeline (In the beginning) operations stream pipeline (At the
chained to each end)
other

5 eg: empty(), stream(), of, ex: filter, map, eg: forEach, collect,
etc flatmap, sorted, toArray, min, max,
etc 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
@Override Notes
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()
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.toLi
st());
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.

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

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

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

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

52
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) {
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());
54
evenNumbers.forEach(System.out::println);
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 56
the highest average salary, and print the
results. Use streams and demonstrate the use of groupingBy, summingDouble,
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_0131
9338454 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)

57
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

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

59
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): " 60
+ totalSalaryParallel);
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.

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

S. Name of
Start Date End Date Portion
No. the
Assessme
nt
As Per As Per
1 Unit Test 1 Unit 1
Academic Academic
Schedule Schedule
As Per As Per
2 FIAT Unit 1 & 2
Academic Academic
Schedule Schedule
As Per As Per
3 Unit Test 2 Unit 3
Academic Academic
Schedule Schedule
As Per As Per
4 SIAT Unit 3 & 4
Academic Academic
Schedule Schedule
As Per As Per
5 Revision 1 Unit 5, 1 & 2
Academic Academic
Schedule Schedule
As Per As Per
6 Revision 2 Unit 3 & 4
Academic Academic
Schedule Schedule
As Per As Per
7 Model All 5 Units
Academic Academic
Schedule Schedule

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

63
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 64
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 65
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 66
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 67
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 68
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 contain
manager. This document proprietary information s
and is intended
community only to the
as intended. respective
If you are notgroup /
the addressee you shouldlearnin
not
disseminate, distribute, or copy through e-mail. Please notify the g 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.

9
0

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy