0% found this document useful (0 votes)
2 views8 pages

Java Lab12r

The document outlines a lab task for Object Oriented Programming through Java, focusing on the Stream API. It includes pre-lab tasks such as listing methods of the BaseStream interface, explaining BinaryOperator, and demonstrating the parallel() method, followed by in-lab tasks that involve implementing programs for reduce operations and using iterators with streams. Additionally, post-lab tasks involve user-driven category processing using Spliterator and tryAdvance() methods.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views8 pages

Java Lab12r

The document outlines a lab task for Object Oriented Programming through Java, focusing on the Stream API. It includes pre-lab tasks such as listing methods of the BaseStream interface, explaining BinaryOperator, and demonstrating the parallel() method, followed by in-lab tasks that involve implementing programs for reduce operations and using iterators with streams. Additionally, post-lab tasks involve user-driven category processing using Spliterator and tryAdvance() methods.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

24CS281 − Object Oriented Programming through Java Lab (IIIrd Semester)

Reg. No.24EU01069

Task 12
The Stream API
Date of the Session: Time of the Session:
Pre-Lab Tasks:
1. List out the methods declared by BaseStream Interface.
Ans: The BaseStream interface is the root interface for Java Streams.
Some important methods declared by the BaseStream interface are:
Iterator<T> iterator() – Returns an iterator for the elements of the stream.
Spliterator<T> spliterator() – Returns a spliterator for the elements of the stream.
boolean isParallel() – Checks if the stream is parallel.
BaseStream<T, S> sequential() – Returns a sequential stream.
BaseStream<T, S> parallel() – Returns a parallel stream.
BaseStream<T, S> unordered() – Returns an unordered stream.
BaseStream<T, S> onClose(Runnable closeHandler) – Registers a handler to be run when the stream is
closed.
void close() – Closes the stream, triggering any registered close handlers.
2. What is BinaryOperator in Stream API?
Ans: A BinaryOperator<T> is a functional interface in Java that represents an operation upon two
operands of the same type, producing a result of the same type.
It extends BiFunction<T, T, T> and is often used in reduction operations such as reduce().
Example:
BinaryOperator<Integer> multiply = (a, b) -> a * b;
int product = [Link](1, 2, 3, 4, 5).reduce(1, multiply);
3. What is parallel() method?
Ans: The parallel() method in the Stream API is used to convert a sequential stream into a parallel stream.
In a parallel stream, tasks are divided into multiple sub-tasks that run concurrently on multiple threads.
It helps improve performance when working with large datasets.
Example:
[Link](1, 2, 3, 4, 5).parallel().forEach([Link]::println);

B. Tech – Artificial Intelligence and Data Science


Page No.
24CS281 − Object Oriented Programming through Java Lab (IIIrd Semester)
Reg. No.24EU01069

4. Explain toList() and toSet() methods.


Ans: Both methods are terminal operations that collect stream elements into collections.
toList() – Collects stream elements into a List.
toSet() – Collects stream elements into a Set.
Examples:
List<Integer> list = [Link](1, 2, 3, 4).toList();
Set<Integer> set = [Link](1, 2, 2, 3).collect([Link]());
5. What is spliterator?
Ans: A Spliterator (Split + Iterator) is a special type of iterator introduced in Java 8.
It is used for traversing and partitioning elements of a source for parallel processing.
Key features:
Can split elements into multiple parts for parallel execution using trySplit().
Can traverse elements using tryAdvance().
Commonly used with Streams.
Example:
List<String> list = [Link]("A", "B", "C", "D");
Spliterator<String> spliterator = [Link]();
[Link]([Link]::println);

In-Lab Tasks:
Program 1: Implement a program to demonstrate reduce operations in Stream API.
Case Study 1: Dynamic Product Calculation Using Java Streams and reduce() Method
A retail analytics team wants to automate the process of calculating the total product of quantity
multipliers entered by users. Instead of using traditional loops, they decide to use Java Stream API for a
modern and functional approach.

The system should:


 Accept a dynamic list of integers (e.g., daily stock multipliers).
 Use the Stream reduce() method to compute the overall product of all numbers.

 Demonstrate both forms of reduction:

B. Tech – Artificial Intelligence and Data Science


Page No.
24CS281 − Object Oriented Programming through Java Lab (IIIrd Semester)
Reg. No.24EU01069

1. Without identity (returns Optional<Integer>)

2. With identity (returns primitive int)

Test Cases:
Test Case 1:
Enter the number of elements: 5
Enter 5 integer values:
Element 1: 1
Element 2: 2
Element 3: 3
Element 4: 4
Element 5: 5

List of numbers: [1, 2, 3, 4, 5]


Product using Optional: 120
Product using identity value: 120

Aim: To implement a Java program that demonstrates the use of reduce() operation in Stream API to
compute the product of a list of integers.
Program Code:
import [Link].*;
import [Link].*;
public class ReduceExample {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the number of elements: ");
int n = [Link]();
List<Integer> numbers = new ArrayList<>();
for (int i = 1; i <= n; i++) {
[Link]("Element " + i + ": ");
[Link]([Link]());
}
[Link]("\nList of numbers: " + numbers);
Optional<Integer> productOptional = [Link]()
.reduce((a, b) -> a * b);
int productWithIdentity = [Link]()

B. Tech – Artificial Intelligence and Data Science


Page No.
24CS281 − Object Oriented Programming through Java Lab (IIIrd Semester)
Reg. No.24EU01069

.reduce(1, (a, b) -> a * b);


[Link]("Product using Optional: " + [Link]());
[Link]("Product using identity value: " + productWithIdentity);
}
}
Output:

Result: Program successfully completed

Program 2: Implement a program to demonstrate iterators and streams in Stream API.


Case Study 1: Use an Iterator with a Stream
A human resources system wants to maintain and display a dynamic list of employee names entered by
users. Instead of using traditional for or while loops, the team decides to use Java Stream API for modern
functional-style processing.
The system should:
 Accept a dynamic list of employee names from the user.
 Convert the list into a Stream.
 Obtain an Iterator from the Stream.
 Display all employee names using the Iterator.

Test Cases:
Test Case 1:
Enter the number of employees: 3
Enter name of employee 1: Prabu
Enter name of employee 2: Arun
Enter name of employee 3: Karthik

B. Tech – Artificial Intelligence and Data Science


Page No.
24CS281 − Object Oriented Programming through Java Lab (IIIrd Semester)
Reg. No.24EU01069

Employee Names:
Prabu
Arun
Karthik

Aim: To demonstrate how to use an Iterator with a Java Stream to display elements in a functional style
Program code:
import [Link].*;
import [Link].*;
public class IteratorStreamExample {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the number of employees: ");
int n = [Link]();
[Link]();
List<String> employees = new ArrayList<>();
for (int i = 1; i <= n; i++) {
[Link]("Enter name of employee " + i + ": ");
[Link]([Link]());
}
[Link]("\nEmployee Names:");
Stream<String> stream = [Link]();
Iterator<String> iterator = [Link]();
while ([Link]()) {
[Link]([Link]());
}
}
}
Output:

B. Tech – Artificial Intelligence and Data Science


Page No.
24CS281 − Object Oriented Programming through Java Lab (IIIrd Semester)
Reg. No.24EU01069

Result: Program successfully completed.

Post-Lab Tasks:
Case Study 1: User-Driven Category Processing using Spliterator and tryAdvance()

A logistics management system wants to process a list of shipment categories entered dynamically by the
user. To make the system modern and flexible, the development team decides to use Java Streams with a
Spliterator to iterate through the elements sequentially.

The system should:


 Accept a dynamic list of shipment categories from the user.

 Convert the list into a Stream.


 Obtain a Spliterator from the Stream.
 Split the Spliterator into two parts using trySplit().
 Display elements from both Spliterators sequentially using tryAdvance().
 Ensure the program uses explicit lambda expressions for processing each element.

Test Cases:
Test Case 1:
Enter the number of shipment categories: 3
Enter category 1: Furniture
Enter category 2: Electronics
Enter category 3: Toys

Elements from the first Spliterator:


Electronics
Toys

Elements from the second Spliterator:


Furniture
Aim: To implement a Java program that uses Spliterator and tryAdvance() to process a list of elements
from a Stream.

Program code:

B. Tech – Artificial Intelligence and Data Science


Page No.
24CS281 − Object Oriented Programming through Java Lab (IIIrd Semester)
Reg. No.24EU01069

import [Link].*;
import [Link].*;
public class SpliteratorExample {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the number of shipment categories: ");
int n = [Link]();
[Link]();
List<String> categories = new ArrayList<>();
for (int i = 1; i <= n; i++) {
[Link]("Enter category " + i + ": ");
[Link]([Link]());
}
Stream<String> stream = [Link]();
Spliterator<String> spliterator1 = [Link]();
Spliterator<String> spliterator2 = [Link]();

[Link]("\nElements from the first Spliterator:");


if (spliterator2 != null) {
[Link](s -> [Link](s));
}
[Link]("\nElements from the second Spliterator:");
[Link](s -> [Link](s));
}
}

Output:

Result: Program successfully completed.

Student’s Signature

B. Tech – Artificial Intelligence and Data Science


Page No.
24CS281 − Object Oriented Programming through Java Lab (IIIrd Semester)
Reg. No.24EU01069

(For Evaluator’s use only)


Marks Secured: _________ out of __________

Faculty Signature

B. Tech – Artificial Intelligence and Data Science


Page No.

You might also like