Java Record
Java Record
ENGINEERING COLLEGE
(An Autonomous Institution)
R.S.M. Nagar, Kavaraipettai -601 206
22CS305
Advanced Java Programming Laboratory
LAB MANUAL
R2022
3rd SEMESTER
22CS305
Advanced Java Programming Laboratory
LAB MANUAL
R2022
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 Experiments
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.
R.M.K. ENGINEERING COLLEGE
(An Autonomous Institution)
OBJECTIVES
• 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.
OUTCOMES
CO1: Utilize the Java Collections Framework to solve complex data structure problems.
CO2: Demonstrate proficiency in Java I/O operations and manage data efficiently.
CO3: Learn to utilize the Stream API for complex data processing by applying functional
programming techniques.
CO4: Understand and implement advanced object serialization techniques.
CO5: Effectively use regular expressions for advanced text processing tasks.
CO6: Build simple applications using advanced java programming concepts.
Ex. No. Date Title Pg.no.
Unit I : 1 Basic Operations On Different Data Structures Arraylist,
Linkedlist, Hashset And Treeset.
Object Serialization
2
3 Implement a program that uses advanced I/O techniques
Implement Custom Stream Generators Using Stream.Generate
Unit V : 1 And Stream.Iterate Methods
2 Advanced Stream Operations
3 Regular Expressions
Unit I
Ex 1: Basic Operations On Different Data Structures Arraylist, Linkedlist, Hashset And Treeset
Output format :
For each size, print the data structure type and the results of the operations:
• Inserting elements: Print the list/set after all elements have been inserted.
• Searching elements: Print whether each element was found or not.
• Deleting elements: Print the list/set after all elements have been deleted.
Algorithm
1. Input Handling:
o Read an integer n representing the number of different sizes to test.
o For each size:
▪ Read the integer size size which specifies the number of integers that will follow.
▪ Read size integers into a list.
2. Processing Each Data Structure:
o For each data structure (ArrayList, LinkedList, HashSet, TreeSet):
1. Insertion:
▪ Insert the integers into the data structure.
▪ Print the state of the data structure after insertion.
2. Searching:
▪ For each integer, check if it is present in the data structure.
▪ Print whether each element was found or not.
3. Deletion:
▪ Clear the data structure.
▪ Print the state of the data structure after deletion.
3. Output:
o Print the results as specified in the output format.
Pseudocode
BEGIN
READ n
FOR i FROM 1 TO n DO
PRINT "Testing with size: " + size
READ size
CREATE a list `elements` to store the size integers
// Inserting elements
FOR each integer in `elements` DO
INSERT integer into the data structure
PRINT the data structure
// Searching elements
FOR each integer in `elements` DO
IF integer is found in the data structure THEN
PRINT integer + " found"
ELSE
PRINT integer + " not found"
// Deleting elements
CLEAR the data structure
PRINT the data structure
END FOR
END
EX 2: Implement A Custom Data Structure That Combines Features Of A List And A Set
Single File Programming Question
You have a Java program that manages a custom data structure called UniqueList. This data structure behaves
like a combination of a list and a set, ensuring all elements are unique while maintaining their insertion order.
Input format :
Input strings are added and removed them to the "UniqueList" and Input an integer to specify the index for
retrieving the element from the "UniqueList".The input terminates when the user types "done".
Output format :
The output of the program is String itself, After entering "done", the program prints the contents of the list.
Sample test cases :
Input 1 :
Red
white
Blue
done
black
done
1
Output 1 :
Red
Added: Red
white
Added: white
Blue
Added: Blue
done
UniqueList: [Red, white, Blue]
Element not found: black
UniqueList after removals: [Red, white, Blue]
Element at index 1: white
Algorithm
1. Initialization:
o Create a custom data structure called UniqueList, which is a list that maintains unique elements
in their order of insertion.
2. Input Handling:
o Continuously read input strings from the user until the user types "done".
o For each input:
▪ If the input is a string, check if the string is already in the UniqueList.
▪ If not, add the string to the UniqueList and print a message confirming the
addition.
▪ If the input is "done", print the contents of the UniqueList.
▪ If the input is an integer, attempt to retrieve the element at that index from the
UniqueList and print the element.
▪ If the input is a string and does not match any current element in UniqueList, print a
message stating the element was not found and that no removal occurred.
3. Edge Cases:
o Handle cases where an integer input is out of bounds of the UniqueList.
o Handle cases where a string to be removed is not present in the UniqueList
Pseudocode
BEGIN
INITIALIZE UniqueList as an empty list
WHILE true DO
READ input from the user
END
EX3: A Java Program To Create A HashMap
Single File Programming Question
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.
Input format :
Get the 5 key value pairs and enter a key to remove,update and check the value.
Output format :
The program outputs whether the key and value is found.
Sample test cases :
Input 1 :
M
10
N
20
O
30
P
40
Q
50
R
S
20
T
505
Output 1 :
Initial map:
P : 40
Q : 50
M : 10
N : 20
O : 30
P : 40
Q : 50
M : 10
N : 20
O : 30
P : 40
Q : 50
S : 20
M : 10
N : 20
O : 30
The map does not contain the key 'T'.
The map does not contain the value 505.
Algorithm
1. Initialization:
o Create a HashMap<String, Integer> to store the key-value pairs.
2. Input Handling:
o Read 5 key-value pairs (string-integer pairs) from the user and add them to the HashMap.
3. Output Initial Map:
o Print all keys and values in the HashMap.
4. Key Removal:
o Read a key from the user to be removed from the HashMap.
o Remove the key and print the updated map.
5. Update Value:
o Read a key and a new value from the user.
o Update the value associated with the key and print the updated map.
6. Check for Specific Key and Value:
o Read a key to check if it exists in the HashMap.
o Print whether the key is found.
o Read a value to check if it exists in the HashMap.
o Print whether the value is found.
Pseudocode
BEGIN
INITIALIZE HashMap<String, Integer> map
END
Unit 2:
Ex 1: Complex Object with Nested Data Structures
Single File Programming Question
Problem description:
Create a Java program that allows users to input details of students in a specific format, serializes this data into
a byte array, and then deserializes it back to verify the integrity of the data.
Implement a StudentDatabase class that contains nested Student objects.
Each Student should have attributes for name (String), age (int), and courses (List of Strings).
The program should allow users to input student details in the format: "Name", Age, "Course1,Course2,..."
(e.g., "John Doe", 20, "Math,Science").
Use Scanner to read input from the user and split the input correctly, handling commas within quoted sections
of the input.
Serialize the StudentDatabase object into a byte array using Java serialization.
Deserialize the byte array back into a StudentDatabase object and print out the details of each student to verify
that the deserialization was successful.
Handle any potential exceptions that may occur during serialization and deserialization.
Input format :
Input consists of Name, Age & Courses
Example:-
"John Doe", 25, "Full stack, Cloud computing"
Output format :
Student{name='John Doe', age=25, courses=[ "Full stack, Cloud computing]}
Pseudocode
WHILE true
READ input from scanner
IF input equals "done"
BREAK
END
Ex. 2: Formatting dates and currencies
Single File Programming Question
Problem description:
Create a Java program that formats dates and currencies according to different locales based on user input.
• Implement a Java program that allows users to input a date and a currency amount.
• The program should format:
• The date according to different locales (US, UK, Germany) using java.time.LocalDate and
java.time.format.DateTimeFormatter.
• The currency amount according to the same locales using java.text.NumberFormat and
java.math.BigDecimal.
• A date in the format YYYY-MM-DD.
• A numeric currency amount (e.g., 1000.50).
• Display an error message if the date input format is incorrect (YYYY-MM-DD).
• Display an error message if the currency amount input is not numeric.
• Print the formatted date and currency for each locale in the specified format.
• Ensure the program closes the Scanner object to release resources properly.
Input format :
Input consists of date and amount
Eg:-
2024-06-18
YYYY-MM-DD
Output format :
Formatted Date:
English (United States): June 18, 2024
English (United Kingdom): June 18, 2024
German (Germany): Juni 18, 2024
Formatted Currency:
English (United States): $1.00
English (United Kingdom): £1.00
German (Germany): 1,00 €
Sample test cases :
Input 1 :
2001-08-03
10000
Output 1 :
Formatted Date:
English (United States): August 3, 2001
English (United Kingdom): August 3, 2001
German (Germany): August 3, 2001
Formatted Currency:
English (United States): $10,000.00
English (United Kingdom): £10,000.00
German (Germany): 10.000,00 €
Input 2 :
2023-01-12
88
Output 2 :
Formatted Date:
English (United States): January 12, 2023
English (United Kingdom): January 12, 2023
German (Germany): Januar 12, 2023
Formatted Currency:
English (United States): $88.00
English (United Kingdom): £88.00
erman(Germany):88,00 €
Algorithm
1. Initialize Scanner:
o Create a Scanner object to read input from the user.
2. Input Handling:
o Read a date string in the format YYYY-MM-DD.
o Read a currency amount as a string.
3. Validate Date Input:
o Attempt to parse the date string using LocalDate.parse with the
DateTimeFormatter.ISO_LOCAL_DATE.
o If parsing fails, print an error message and exit.
4. Validate Currency Input:
o Attempt to parse the currency amount as a BigDecimal.
o If parsing fails, print an error message and exit.
5. Format and Print Date:
o Define DateTimeFormatter instances for formatting the date in the US, UK, and Germany
locales.
o Format and print the date for each locale.
6. Format and Print Currency:
o Use NumberFormat for formatting the currency amount according to the US, UK, and Germany
locales.
o Format and print the currency for each locale.
7. Close Scanner:
o Close the Scanner object to release resources.
Pseudocode
BEGIN
// Step 1: Initialize Scanner
CREATE Scanner scanner = new Scanner(System.in)
END
Ex. 3: Implement A Java Program To Do File Operations
Single File Programming Question
Problem description:
You are developing a command-line task management system to help users organize their tasks efficiently.
The system allows users to perform CRUD operations (Create, Read, Update, Delete) on a list of tasks stored
in memory. Each task is represented as a string.
• 1. Create (Insert): Allow the user to add a new task to the task list.
• 2. Update: Allow the user to update an existing task in the list.
• 3. Delete: Allow the user to delete a task from the list.
• 4. Display: Display all tasks currently in the list.
• 0. Exit: Exit the program.
Input format :
Input consists of the menu option and data
option - 1
insert data - "iamNeo"
option - 2
update data - "neoColab"
option - 3
Deleted!
option - 0
Exiting...
Output format :
1. Create (Insert)
2. Update
3. Delete
0. Exit
Enter your choice: Inserted data: hello world
1. Create (Insert)
2. Update
3. Delete
0. Exit
Enter your choice: Updated data: iamneo
1. Create (Insert)
2. Update
3. Delete
0. Exit
Enter your choice: Deleted!
1. Create (Insert)
2. Update
3. Delete
0. Exit
Enter your choice: Exiting...
Sample test cases :
Input 1 :
1
webpage
2
website
3
0
Output 1 :
1. Create (Insert)
2. Update
3. Delete
0. Exit
Inserted data: webpage
1. Create (Insert)
2. Update
3. Delete
0. Exit
Updated data: website
1. Create (Insert)
2. Update
3. Delete
0. Exit
Deleted!
1. Create (Insert)
2. Update
3. Delete
0. Exit
Exiting...
Input 2 :
1
hello world
2
iamneo
3
0
Output 2 :
1. Create (Insert)
2. Update
3. Delete
0. Exit
Inserted data: hello world
1. Create (Insert)
2. Update
3. Delete
0. Exit
Updated data: iamneo
1. Create (Insert)
2. Update
3. Delete
0. Exit
Deleted!
1. Create (Insert)
2. Update
3. Delete
0. Exit
Exiting...
Algorithm
1. Initialize the Task List:
o Create a List<String> to store tasks.
2. Display Menu Options:
o Print the menu with options:
1. Create (Insert)
2. Update
3. Delete
4. Exit
3. User Input:
o Use Scanner to read the user's choice from the menu.
4. Perform Operations Based on User Choice:
o Option 1: Create (Insert)
▪ Prompt the user to enter the task to be added.
▪ Add the task to the task list.
▪ Print a confirmation message.
o Option 2: Update
▪ Check if the task list is not empty.
▪ Prompt the user to enter the new task.
▪ Replace the last task with the new task.
▪ Print a confirmation message.
o Option 3: Delete
▪ Check if the task list is not empty.
▪ Remove the last task from the list.
▪ Print a confirmation message.
o Option 0: Exit
▪ Print an exit message.
▪ Terminate the program.
5. Loop Until Exit:
o Continuously display the menu and perform operations until the user chooses to exit.
6. Handle Edge Cases:
o Handle cases where the user tries to update or delete a task when the task list is empty.
Pseudocode
BEGIN
// Step 1: Initialize the Task List
CREATE List<String> taskList = new ArrayList<>()
CREATE Scanner scanner = new Scanner(System.in)
int choice
DO
// Step 2: Display Menu Options
PRINT "1. Create (Insert)"
PRINT "2. Update"
PRINT "3. Delete"
PRINT "0. Exit"
PRINT "Enter your choice: "
ELSE
PRINT "Invalid choice, please try again."
END IF
WHILE choice != 0
// Step 5: Close Scanner
scanner.close()
END
Unit 3:
Ex. 1: Stream Operations - Filtering, Mapping, And Reducing
Single File Programming Question
You are working as a data engineer for a company that processes large datasets of customer transactions. Your
task is to create a program that performs various stream operations like filtering, mapping, and reducing on a
list of transaction data. Each transaction is represented as an object with the following fields: transactionId,
customerId, amount, and status.
Your task is to perform the following operations:
Pseudocode
CLASS Transaction
ATTRIBUTES
String transactionId
String customerId
double amount
String status
CONSTRUCTOR
Transaction(String transactionId, String customerId, double amount, String status)
this.transactionId = transactionId
this.customerId = customerId
this.amount = amount
this.status = status
BEGIN
// Step 1: Initialize Scanner and List
CREATE Scanner scanner = new Scanner(System.in)
CREATE List<Transaction> transactions = new ArrayList<>()
Example:
Assume the input text file (sentences.txt) contains the following content:
Output:
sample
sentence
quick
brown
fox
jumps
lazy
dog
Hello
world!
today?
Input format :
The input consists of a text file containing multiple sentences.
Output format :
The output should display the remaining words after stopwords have been filtered out from each sentence.
Algorithm
1. Load Stopwords:
o Create a list or set of stopwords like "the," "a," "an," "is," "on," etc.
2. Read the Input File:
o Open and read the contents of the text file (sentences.txt).
o Split the file content into sentences using newline characters.
3. Process Each Sentence:
o For each sentence, split it into words.
o Filter out the stopwords from the list of words.
o Join the remaining words back into a sentence.
4. Output the Results:
o For each processed sentence, print the remaining words.
Pseudocode
BEGIN
// Step 1: Load the stopwords
SET stopwords = ["the", "a", "an", "is", "on", "and", "of", "in", "to", "with", ...]
Task:
Write a Java program that reads the contents of a text file, tokenizes the text into sentences using the
StringTokenizer class, and prints each sentence on a new line. Your program should handle different types of
sentence delimiters such as periods (.), exclamation marks (!), and question marks (?). Additionally, ensure
that the program can handle multiple lines of text and extra whitespaces gracefully.
Input format :
The program should read the contents of a text file specified by the user.
The program should handle the file not being found or any other I/O exceptions gracefully.
Output format :
Each sentence should be printed on a new line after being tokenized.
Trim any leading or trailing whitespace from each sentence before printing.
Sample test cases :
Input 1 :
Is this a question? Yes, it is! This is a statement.
Output 1 :
Is this a question
Yes, it is
This is a statement
Input 2 :
This is the first line. This is the second line! Is this the third line?
Output 2 :
This is the first line
This is the second line
Is this the third line
Algorithm
1. Load and Open the Text File:
o Prompt the user for the file path of the text file.
o Attempt to open the file and read its contents.
o Handle any potential I/O exceptions (e.g., file not found) gracefully.
2. Initialize StringTokenizer:
o Create a StringTokenizer instance to tokenize the text.
o Specify the delimiters as periods (.), exclamation marks (!), and question marks (?).
3. Tokenize the Text into Sentences:
o Use the StringTokenizer to extract sentences.
o For each token (sentence), trim leading and trailing whitespace.
4. Output the Sentences:
o Print each sentence on a new line.
5. Handle Exceptions:
o Ensure that any I/O exceptions are caught and a meaningful error message is displayed to the
user.
Pseudocode
BEGIN
TRY
// Step 1: Load and open the text file
PROMPT user for the file path
OPEN file with the specified path
// Step 4: Tokenize the text into sentences and print each sentence
WHILE tokenizer has more tokens DO
SET sentence = tokenizer.nextToken().trim()
PRINT sentence
END WHILE
CATCH IOException
PRINT "An error occurred while reading the file. Please check the file path and try again."
END TRY
END
Ex. 2: Object Serialization
Single File Programming Question
Scenario:
Imagine you are tasked with developing a Java application that manages serialization and deserialization of
Person and Employee objects. Your application needs to read input data from standard input, create
corresponding objects based on the input format, serialize these objects to a file named objects.ser, and finally
deserialize them to verify the process.
Tasks:
1. Implement the Person and Employee classes with appropriate constructors and toString() methods to
represent individuals with basic details.
2. Develop a Java class SerializationExample with methods to parse input, serialize objects, and
deserialize objects from a file.
3. Ensure that the program handles input dynamically from standard input (System.in), splitting input
lines by commas to distinguish between Person and Employee objects.
4. Serialize the objects into a file objects.ser and print a confirmation message upon successful
serialization.
5. Deserialize the objects from objects.ser and print each object to verify successful deserialization.
Input format :
1. Input will consist of multiple lines, each containing a comma-separated string.
2. Each line represents an object of either Person or Employee.
3. For Person: "Person,Name,Age"
4. For Employee: "Employee,Name,Age,EmployeeId,Department"
5. Age should be an integer value. EmployeeId and Department may be optionally null.
Output format :
1. Upon successful execution, the program should output the serialized objects confirmation message.
2. For each object deserialized, print its details formatted as specified in toString() methods
of Person and Employee
Sample test cases :
Input 1 :
Person,John Doe,30
Employee,Jane Smith,40,E123,HR
Output 1 :
Objects have been serialized to objects.ser
Deserialized Object: Person [name=John Doe, age=30]
Deserialized Object: Employee [employeeId=E123, department=HR, Person [name=Jane Smith, age=40]]
Input 2 :
Employee,Jane Smith,40,null,null
Output 2 :
Objects have been serialized to objects.ser
Deserialized Object: Employee [employeeId=null, department=null, Person [name=Jane Smith, age=40]]
Note :
The program will be evaluated only after the “Submit Code” is clicked.
Extra spaces and new line characters in the program output will result in the failure of the test case.
Algorithm
1. Define Classes:
o Person Class:
▪ Attributes: name, age
▪ Methods: Constructor, toString()
o Employee Class (extends Person):
▪ Additional Attributes: employeeId, department
▪ Methods: Constructor, toString()
2. Read and Parse Input:
o Read multiple lines of input from standard input.
o Parse each line to determine if it represents a Person or Employee and extract attributes.
3. Create Objects:
o Create instances of Person or Employee based on parsed input.
4. Serialize Objects:
o Serialize the created objects to a file named objects.ser.
o Print a confirmation message upon successful serialization.
5. Deserialize Objects:
o Read the serialized objects from objects.ser.
o Print each deserialized object's details using their toString() methods.
6. Handle Exceptions:
o Ensure that any I/O or serialization/deserialization exceptions are handled gracefully.
Pseudocode
BEGIN
// Step 1: Define classes
CLASS Person
Attributes: name, age
CONSTRUCTOR(name, age)
METHOD toString() RETURNS "Person [name=name, age=age]"
Tasks:
1. Implement a method testPipedStreams that reads a string from a PipedInputStream after writing it to a
PipedOutputStream.
2. Implement a method testSequenceInputStream that concatenates the contents of two byte arrays using
SequenceInputStream.
3. Implement a method testPushbackInputStream that demonstrates the pushback functionality by reading
a byte, pushing it back, and reading it again.
4. Implement a method testMultiplePushbackInputStream that demonstrates the pushback functionality
with multiple pushbacks and reads.
5. Implement a method testMultipleSequenceInputStream that concatenates the contents of multiple byte
arrays using SequenceInputStream.
Input format :
1. First line: the name of the test case to run
(testPipedStreams, testSequenceInputStream, testPushbackInputStream, testMultiplePushbackInputSt
ream, testMultipleSequenceInputStream).
2. Subsequent lines: inputs required for the specified test case.
Output format :
1. The result of the executed test case, printed to the console.
Sample test cases :
Input 1 :
testPipedStreams
Hello World
Output 1 :
Read from PipedInputStream: Hello World
Input 2 :
testMultipleSequenceInputStream
Advanced
Java
IO
Techniques
Output 2 :
Concatenated Stream: AdvancedJavaIOTechniques
Note :
The program will be evaluated only after the “Submit Code” is clicked.
Extra spaces and new line characters in the program output will result in the failure of the test case.
Algorithm
1. Read the Test Case:
o Read the first line to determine which test case to execute.
o Read subsequent lines as required by the selected test case.
2. Implement Test Methods:
o testPipedStreams:
▪ Create a PipedOutputStream and a PipedInputStream.
▪ Connect them using PipedInputStream and PipedOutputStream.
▪ Write the input string to PipedOutputStream.
▪ Read from PipedInputStream and print the result.
o testSequenceInputStream:
▪ Create two byte arrays from the input lines.
▪ Create a SequenceInputStream with these byte arrays.
▪ Read from the SequenceInputStream and concatenate the results.
▪ Print the concatenated string.
o testPushbackInputStream:
▪ Create a PushbackInputStream with a byte array.
▪ Read a byte from the PushbackInputStream.
▪ Push the byte back and read it again.
▪ Print the results of both reads.
o testMultiplePushbackInputStream:
▪ Create a PushbackInputStream with a byte array.
▪ Perform multiple pushbacks and reads.
▪ Print the results of the reads.
o testMultipleSequenceInputStream:
▪ Create multiple byte arrays from the input lines.
▪ Use SequenceInputStream to concatenate these byte arrays.
▪ Read from the SequenceInputStream and concatenate the results.
▪ Print the concatenated string.
3. Handle Exceptions:
o Ensure that any I/O or stream-related exceptions are caught and handled.
Pseudocode
BEGIN
FUNCTION main()
READ first line as testCase
READ subsequent lines as inputs
FUNCTION testPipedStreams(inputs)
CREATE PipedOutputStream
CREATE PipedInputStream connected to PipedOutputStream
WRITE inputs[0] to PipedOutputStream
READ from PipedInputStream
PRINT "Read from PipedInputStream: " + data
END FUNCTION
FUNCTION testSequenceInputStream(inputs)
CREATE byte arrays from inputs
CREATE SequenceInputStream with byte arrays
READ from SequenceInputStream
CONCATENATE and PRINT the result
END FUNCTION
FUNCTION testPushbackInputStream(inputs)
CREATE PushbackInputStream with byte array from inputs
READ a byte
PUSH byte back
READ the byte again
PRINT results of both reads
END FUNCTION
FUNCTION testMultiplePushbackInputStream(inputs)
CREATE PushbackInputStream with byte array from inputs
PERFORM multiple pushbacks and reads
PRINT results of reads
END FUNCTION
FUNCTION testMultipleSequenceInputStream(inputs)
CREATE byte arrays from inputs
CREATE SequenceInputStream with byte arrays
READ from SequenceInputStream
CONCATENATE and PRINT the result
END FUNCTION
END
Unit 5:
Ex. 1: Implement Custom Stream Generators Using Stream.Generate And Stream.Iterate Methods
Single File Programming Question
Develop a program to generate a custom sequence of numbers for two purposes: generating the Fibonacci
sequence. Implement these using Stream.iterate methods in Java.
Input format :
Line 1 : Input for Fibonacci sequence limit
10
Output format :
Line 1 : Fibonacci Sequence: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
FUNCTION generateFibonacciStream(n)
RETURN Stream.iterate(
Tuple2(0, 1),
previous -> Tuple2(previous[1], previous[0] + previous[1]),
tuple -> tuple[0]
)
.limit(n)
END FUNCTION
END
Ex.2: Advanced Stream Operations
Single File Programming Question
Develop a program where we have a list of employees, each associated with multiple projects they have
worked on. take input from the user for creating employees and their projects, then demonstrate various stream
operations like flatMap, chaining of stream operations, and using peek for debugging purposes.
Output :
FlatMapping to get all projects across all employees
Chaining stream operations: Filter employees who worked on projects with budget over 10000 and calculate
total budget
Input format :
Input line 1 : Enter number of employees
line 2 : Enter employee ID
line 3 : Enter employee name
line 4 :Enter number of projects for this employee
line 5 : Enter project name
line 6 : Enter project duration in months
line 7 : Enter project budget
Output format :
The output prints the project details with budget and duration.
Sample test cases :
Input 1 :
1
12
Ram
1
ABCD
6
6000
Output 1 :
Project 1:
All Projects:
Project{projectName='ABCD', durationMonths=6, projectBudget=6000.0}
Total budget for projects with budget over 10000: 0.0
All Projects:
Project{projectName='XYZ', durationMonths=8, projectBudget=8000.0}
CREATE a new Employee object with the given details and project list
ADD the Employee object to the list of employees
END FUNCTION
END
Ex. 3: Regular Expressions
Single File Programming Question
Demonstrate how to use regular expressions in Java to perform common string manipulation tasks such as
splitting strings, replacing text, and extracting specific patterns.
Input format :
Input line 1: Enter a comma-separated list of names
Input line 2:Enter the name to replace
Input line 3:Enter the replacement name
Input line 4:Enter the starting letter to extract names (case-sensitive)
Output format :
Splitting string into names:
Harshit
Shyam
Ravi
Virat
Replacing 'Ravi' with 'Harshit':
Harshit,Shyam,Harshit,Virat
Sample test cases :
Input 1 :
Harshit,Shyam,Ravi,Virat
Ravi
Harshit
H
Output 1 :
END FUNCTION
END