0% found this document useful (0 votes)
7 views18 pages

Unit 3 Session 9

The document provides an overview of the Java Stream API introduced in Java 8, detailing its features, operations, and examples of usage in filtering collections and file operations. It explains the concepts of intermediate and terminal operations, including common methods like map, filter, and collect. Additionally, it includes practical code examples demonstrating filtering collections with and without streams, as well as reading and processing data from files.

Uploaded by

gnanavel.m
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)
7 views18 pages

Unit 3 Session 9

The document provides an overview of the Java Stream API introduced in Java 8, detailing its features, operations, and examples of usage in filtering collections and file operations. It explains the concepts of intermediate and terminal operations, including common methods like map, filter, and collect. Additionally, it includes practical code examples demonstrating filtering collections with and without streams, as well as reading and processing data from files.

Uploaded by

gnanavel.m
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/ 18

KGiSL Institute of Technology

(Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai)


Recognized by UGC, Accredited by NBA (IT)
365, KGiSL Campus, Thudiyalur Road, Saravanampatti, Coimbatore – 641035.

Department of Computer Science and Engineering

Name of the Faculty : Gnanavel M


Subject Name & Code : 24UCS312 - OBJECT ORIENTED PROGRAMMING
Branch & Department : BE.CSE
Year & Semester : II Year / III Sem
Academic Year :2025-2026
Java Stream API

• Java provides a new additional package in Java 8 called


java.util.stream. This package consists of classes, interfaces and enum
to allows functional-style operations on the elements. You can use
stream by importing java.util.stream package.
Features…
• Stream does not store elements. It simply conveys elements from a
source such as a data structure, an array, or an I/O channel, through a
pipeline of computational operations.
• Stream is functional in nature. Operations performed on a stream does
not modify it's source. For example, filtering a Stream obtained from a
collection produces a new Stream without the filtered elements, rather
than removing elements from the source collection.
• Stream is lazy and evaluates code only when required.
• The elements of a stream are only visited once during the life of a
stream. Like an Iterator, a new stream must be generated to revisit the
same elements of the source.
Various Operations

1.Intermediate Operations
• Intermediate operations in Java Streams return another Stream.
• They are typically used to transform or filter the elements of the
original Stream.
• Since they are lazy, meaning they do not perform any processing until
a terminal operation is called, multiple intermediate operations can
be chained together.
Common Intermediate Operations:
• map(Function<T, R>): Transforms each element of the Stream into
another form using the provided function.
• filter(Predicate<T>): Selects elements from the Stream based on a
specified condition.
• flatMap(Function<T, Stream<R>>): Transforms each element into
zero or more elements by applying a function that returns a stream
for each element.
• distinct(): Removes duplicate elements from the Stream
Contd..
• sorted(): Sorts the elements of the Stream.
• limit(long n): Truncates the Stream to be no longer than the specified
size.
• skip(long n): Skips the first n elements of the Stream.
• peek(Consumer<T>): Performs a specified action on each element of
the Stream without consuming the elements.
Contd..
• 2. Terminal Operations
• Terminal operations are those operations that consume the Stream
and produce a result, such as a value, a collection, or even a side
effect.
• Once a terminal operation is invoked, the Stream is processed and
cannot be reused.
Common Terminal Operations:
• forEach(Consumer<T>): Acts as each element of the Stream.
• collect(Collector<T, A, R>): Reduces the elements of the Stream into a
mutable result container, such as a list or a map.
• reduce(BinaryOperator<T>): Reduces the elements of the Stream to a
single value using an associative accumulation function.
• count(): Returns the count of elements in the Stream.
Contd..
• anyMatch(Predicate<T>): Returns true if any element of the Stream
matches the given predicate.
• allMatch(Predicate<T>): Returns true if all elements of the Stream
match the given predicate.
• noneMatch(Predicate<T>): Returns true if no elements of the Stream
match the given predicate.
• findFirst(): Returns an Optional describing the first element of the
Stream, or an empty Optional if the Stream is empty.
• findAny(): Returns an Optional describing some element of the
Stream, or an empty Optional if the Stream is empty.
Short-Circuit Operations

• Short-circuit operations are a subset of terminal operations that do


not need to process the entire Stream to produce a result. They can
provide an early exit from the stream processing pipeline, potentially
saving computation time.
Operations..
• anyMatch(Predicate<T>): Stops processing and returns true if any
element matches the given predicate.
• allMatch(Predicate<T>): Stops processing and returns false if any
element does not match the given predicate.
• noneMatch(Predicate<T>): Stops processing and returns true if no
elements match the given predicate.
• findFirst(): Returns the first element encountered in the Stream and
then stops processing.
• findAny(): Returns any element encountered in the Stream and then
stops processing.
Java Example: Filtering Collection without using Stream

• import java.util.*;
• class Product{
• int id;
• String name;
• float price;
• public Product(int id, String name, float price) {
• this.id = id;
• this.name = name;
• this.price = price;
• }
• }
Contd..
• public class JavaStreamExample {
• public static void main(String[] args) {
• List<Product> productsList = new ArrayList<Product>();
• //Adding Products
• productsList.add(new Product(1,"HP Laptop",25000f));
• productsList.add(new Product(2,"Dell Laptop",30000f));
• productsList.add(new Product(3,"Lenevo Laptop",28000f));
• productsList.add(new Product(4,"Sony Laptop",28000f));
• productsList.add(new Product(5,"Apple Laptop",90000f));
• List<Float> productPriceList = new ArrayList<Float>();
• for(Product product: productsList){
• // filtering data of list
• if(product.price<30000){
• productPriceList.add(product.price); // adding price to a productPriceList
• }
• }
• System.out.println(productPriceList); // displaying data
• }
• }
Java Stream Example: Filtering Collection by Using
Stream

• import java.util.*;
• import java.util.stream.Collectors;
• class Product{
• int id;
• String name;
• float price;
• public Product(int id, String name, float price) {
• this.id = id;
• this.name = name;
• this.price = price;
• }
• }
Example

• public class JavaStreamExample {


• public static void main(String[] args) {
• List<Product> productsList = new ArrayList<Product>();
• //Adding Products
• productsList.add(new Product(1,"HP Laptop",25000f));
• productsList.add(new Product(2,"Dell Laptop",30000f));
• productsList.add(new Product(3,"Lenevo Laptop",28000f));
• productsList.add(new Product(4,"Sony Laptop",28000f));
• productsList.add(new Product(5,"Apple Laptop",90000f));
• List<Float> productPriceList2 =productsList.stream()
• .filter(p -> p.price > 30000)// filtering data
• .map(p->p.price) // fetching price
• .collect(Collectors.toList()); // collecting as list
• System.out.println(productPriceList2);
• }
• }
Java Stream: File Operation

• Java Streams API, introduced in Java 8, provides a very efficient and


expressive way to handle streams of data, including files.
• “streams" refers to a sequence of elements supporting sequential and
parallel aggregate operations, not to be confused
with InputStream and OutputStream from I/O streams.
• Using the Streams API to manipulate file data involves reading from
files, processing the data line-by-line or in bulk, and often writing
results to another file. It is typically achieved using the Files class in
the java.nio.file package, which integrates seamlessly with the
Streams API.
Example
• import java.io.BufferedReader;
• import java.io.FileReader;
• import java.io.IOException;
• import java.util.ArrayList;
• import java.util.List;
• // Define a public class named FileReadExample
• public class FileReadExample {
• // Define a private static method that filters strings by length and converts them to uppercase
• private static List<String> filterAndConvertToUpper(List<String> lines, int length) {
• // Create a new ArrayList to store filtered and modified strings
• List<String> filteredStrings = new ArrayList<>();
• // Iterate over each string in the list provided
• for (String line : lines) {
• // Check if the length of the string equals the specified length
• if (line.length() == length) {
• // Convert the string to uppercase and add it to the list of filtered strings
• filteredStrings.add(line.toUpperCase());
• }
• }
• // Return the list of filtered and converted strings
• return filteredStrings;
• }
Contd..
• public static void main(String[] args) {
• // Specify the path to the file that will be read
• String fileName = "D://javatpoint//CustomFileReader.txt";
• // Initialize a new ArrayList to store the lines read from the file
• List<String> lines = new ArrayList<>();
• // Use try-with-resources to ensure the BufferedReader is closed properly
• try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
• String line;
• // Read each line of the file until no more lines are found
• while ((line = br.readLine()) != null) {
• // Add each line to the list of lines
• lines.add(line);
• // Print out each line that is read, for debugging purposes
• System.out.println("Read line: " + line);
• }
• // Call the filterAndConvertToUpper method to process the lines and store the result
• List<String> filteredStrings = filterAndConvertToUpper(lines, 5);
• // Print out the list of filtered and converted strings
• System.out.println("Filtered strings with length 5 (converted to uppercase): " + filteredStrings);
• } catch (IOException e) {
• // Catch and print details of any IOException that occurs during file reading
• e.printStackTrace();
• }
• }
• }

You might also like