Advanced Java Unit 3 Digital Notes
Advanced Java Unit 3 Digital Notes
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
11 Part B Questions 78
13 Real-Time Applications 80
15 Assessment Schedule 84
5
1. Course Objectives
OBJECTIVES: ( To be updated )
Gain a comprehensive understanding of the Java Collections Framework and its various
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
Understand advanced Stream API features and gain proficiency in using regular expressions
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
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.
tasks such as splitting strings, replacing text, and extracting specific patterns.
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.
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
10
4. Course Outcomes
At the end of this course, the students will be able to:
CO5 Effectively use regular expressions for advanced text processing tasks. 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
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
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
// 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.
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:
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:
INTERMEDIATE OPERATIONS
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)
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
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;
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;
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;
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");
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;
System.out.println(sortedList);
}
}
[one, three, two]
8. Lecture Notes
METHODS OF STREAM INTERFACE
TERMINAL OPERATIONS
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)
7 boolean
Checks if no
noneMatch(Predicate stream.noneMatch(s ->
NoneMatch elements match
<? super T> s.length() > 1)
the given predicate
predicate)
28
8. Lecture Notes
METHODS OF STREAM INTERFACE
TERMINAL OPERATIONS
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
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
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
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
);
// 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);
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);
}
OUTPUT
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
// Mapping to squares
List<Integer> squares = numbers.stream()
.map(n -> n * n)
.toList();
System.out.println("Squares: " + squares);
import java.util.stream.Stream;
import java.util.stream.IntStream;
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
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;
OUTPUT
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
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
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
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
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
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;
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;
54
12. Supportive Online Certifications
55
13. Real Time Applications
Mobile Applications
Artificial intelligence
Gaming Applications
Business Applications
Embedded Systems
Scientific Applications
Distributed Applications
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;
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.
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.
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
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
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
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.
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
4 65
17. Mini Project - V
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.
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