GFG Day 18: Stream, Optional Class & Employee Data Analyzer Project

sri parthusri parthu
16 min read

Stream in Java

  • A Stream in Java is a sequence of elements that supports functional-style operations. It is not a data structure, but a pipeline to process collections (like List, Set) in a declarative way.

Use of Stream in Java

  • Concise & readable code

  • Functional programming style

  • Easy to perform filtering, mapping, sorting, etc.

  • Supports parallel processing (for performance)

How to Create a Java Stream?

  • Java Stream Creation is one of the most basic steps before considering the functionalities of the Java Stream. Below is the syntax given for declaring a Java Stream.

Syntax

Stream<T> stream;

Here, T is either a class, object, or data type depending upon the declaration.

Java Stream Features

  • The features of Java streams are mentioned below:

    • A stream is not a data structure; instead, it takes input from the Collections, Arrays, or I/O channels.

    • Streams don’t change the original data structure, they only provide the result as per the pipelined methods.

    • Each intermediate operation is lazily executed and returns a stream as a result, hence, various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result.

Different Operations On Streams

There are two types of Operations in Streams:

  1. Intermediate Operations

  2. Terminal Operations

Intermediate Operations

Java Stream Operations

Intermediate Operations are the types of operations in which multiple methods are chained in a row.

Characteristics of Intermediate Operations

  • Methods are chained together.

  • Intermediate operations transform a stream into another stream.

  • It enables the concept of filtering where one method filters data and passes it to another method after processing.

Benefit of Java Stream

  • There are some benefits because of which we use Stream in Java as mentioned below:

    • No Storage

    • Pipeline of Functions

    • Laziness

    • Can be infinite

    • Can be parallelized

    • Can be created from collections, arrays, Files Lines, Methods in Stream, IntStream etc.

Important Intermediate Operations

  • There are a few Intermediate Operations mentioned below:

1. map(): The map method is used to return a stream consisting of the results of applying the given function to the elements of this stream.

Syntax:

<R> Stream<R> map(Function<? super T, ? extends R> mapper)

2. filter(): The filter method is used to select elements as per the Predicate passed as an argument.

Syntax:

Stream<T> filter(Predicate<? super T> predicate)

3. sorted(): The sorted method is used to sort the stream.

Syntax:

Stream<T> sorted()
Stream<T> sorted(Comparator<? super T> comparator)

4. flatMap(): The flatMap operation in Java Streams is used to flatten a stream of collections into a single stream of elements.

Syntax:

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)

5. distinct(): Removes duplicate elements. It returns a stream consisting of the distinct elements (according to Object.equals(Object)).

Syntax:

Stream<T> distinct()

6. peek(): Performs an action on each element without modifying the stream. It returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.

Syntax:

Stream<T> peek(Consumer<? super T> action)

Java program that demonstrates the use of all the intermediate operations:

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class StreamIntermediateOperationsExample {
    public static void main(String[] args) {
        // List of lists of names
        List<List<String>> listOfLists = Arrays.asList(
            Arrays.asList("Reflection", "Collection", "Stream"),
            Arrays.asList("Structure", "State", "Flow"),
            Arrays.asList("Sorting", "Mapping", "Reduction", "Stream")
        );

        // Create a set to hold intermediate results
        Set<String> intermediateResults = new HashSet<>();

        // Stream pipeline demonstrating various intermediate operations
        List<String> result = listOfLists.stream()
            .flatMap(List::stream)               // Flatten the list of lists into a single stream
            .filter(s -> s.startsWith("S"))      // Filter elements starting with "S"
            .map(String::toUpperCase)            // Transform each element to uppercase
            .distinct()                          // Remove duplicate elements
            .sorted()                            // Sort elements
            .peek(s -> intermediateResults.add(s)) // Perform an action (add to set) on each element
            .collect(Collectors.toList());       // Collect the final result into a list

        // Print the intermediate results
        System.out.println("Intermediate Results:");
        intermediateResults.forEach(System.out::println);

        // Print the final result
        System.out.println("Final Result:");
        result.forEach(System.out::println);
    }
}

Output

Intermediate Results:
STRUCTURE
STREAM
STATE
SORTING
Final Result:
SORTING
STATE
STREAM
STRUCTURE

Explanation of the above Program:

List of Lists Creation:

  • The listOfLists is created as a list containing other lists of strings.

Stream Operations:

  • Below are the stream operations

    • flatMap(List::stream): Flattens the nested lists into a single stream of strings.

    • filter(s -> s.startsWith("S")): Filters the strings to only include those that start with "S".

    • map(String::toUpperCase): Converts each string in the stream to uppercase.

    • distinct(): Removes any duplicate strings.

    • sorted(): Sorts the resulting strings alphabetically.

    • peek(...): Adds each processed element to the intermediateResults set for intermediate inspection.

    • collect(Collectors.toList()): Collects the final processed strings into a list called result.

  • The program prints the intermediate results stored in the intermediateResults set. Finally, it prints the result list, which contains the fully processed strings after all stream operations.

  • This example showcases how Java Streams can be used to process and manipulate collections of data in a functional and declarative manner, applying transformations and filters in a sequence of operations.

Terminal Operations

  • Terminal Operations are the type of Operations that return the result. These Operations are not processed further just return a final result value.

Important Terminal Operations

  • There are a few Terminal Operations mentioned below:

1. collect(): The collect method is used to return the result of the intermediate operations performed on the stream.

Syntax:

<R, A> R collect(Collector<? super T, A, R> collector)

2. forEach(): The forEach method is used to iterate through every element of the stream.

Syntax:

void forEach(Consumer<? super T> action)

3. reduce(): The reduce method is used to reduce the elements of a stream to a single value. The reduce method takes a BinaryOperator as a parameter.

Syntax:

T reduce(T identity, BinaryOperator<T> accumulator)
Optional<T> reduce(BinaryOperator<T> accumulator)

4. count(): Returns the count of elements in the stream.

Syntax:

long count()

5. findFirst(): Returns the first element of the stream, if present.

Syntax:

Optional<T> findFirst()

6. allMatch(): Checks if all elements of the stream match a given predicate.

Syntax:

boolean allMatch(Predicate<? super T> predicate)

7. anyMatch(): Checks if any element of the stream matches a given predicate.

Syntax:

boolean anyMatch(Predicate<? super T> predicate)

Here ans variable is assigned 0 as the initial value and i is added to it.

Note: Intermediate Operations are running based on the concept of Lazy Evaluation, which ensures that every method returns a fixed value(Terminal operation) before moving to the next method.

Java Program Using all Terminal Operations:

import java.util.*;
import java.util.stream.Collectors;

public class StreamTerminalOperationsExample {
    public static void main(String[] args) {
        // Sample data
        List<String> names = Arrays.asList(
            "Reflection", "Collection", "Stream",
            "Structure", "Sorting", "State"
        );

        // forEach: Print each name
        System.out.println("forEach:");
        names.stream().forEach(System.out::println);

        // collect: Collect names starting with 'S' into a list
        List<String> sNames = names.stream()
                                   .filter(name -> name.startsWith("S"))
                                   .collect(Collectors.toList());
        System.out.println("\ncollect (names starting with 'S'):");
        sNames.forEach(System.out::println);

        // reduce: Concatenate all names into a single string
        String concatenatedNames = names.stream().reduce(
            "",
            (partialString, element) -> partialString + " " + element
        );
        System.out.println("\nreduce (concatenated names):");
        System.out.println(concatenatedNames.trim());

        // count: Count the number of names
        long count = names.stream().count();
        System.out.println("\ncount:");
        System.out.println(count);

        // findFirst: Find the first name
        Optional<String> firstName = names.stream().findFirst();
        System.out.println("\nfindFirst:");
        firstName.ifPresent(System.out::println);

        // allMatch: Check if all names start with 'S'
        boolean allStartWithS = names.stream().allMatch(
            name -> name.startsWith("S")
        );
        System.out.println("\nallMatch (all start with 'S'):");
        System.out.println(allStartWithS);

        // anyMatch: Check if any name starts with 'S'
        boolean anyStartWithS = names.stream().anyMatch(
            name -> name.startsWith("S")
        );
        System.out.println("\nanyMatch (any start with 'S'):");
        System.out.println(anyStartWithS);
    }
}

Output

forEach:
Reflection
Collection
Stream
Structure
Sorting
State

collect (names starting with 'S'):
Stream
Structure
Sorting
State

reduce (concatenated names):
Reflection Collection Stream Structure Sorting State

count:
6

findFirst:
Reflection

allMatch (all start with 'S'):
false

anyMatch (any start with 'S'):
true

Explanation of the above Program:

List Creation:

  • The names list is created with sample strings.

Stream Operations:

  • forEach: Prints each name in the list.

  • collect: Filters names starting with 'S' and collects them into a new list.

  • reduce: Concatenates all names into a single string.

  • count: Counts the total number of names.

  • findFirst: Finds and prints the first name in the list.

  • allMatch: Checks if all names start with 'S'.

  • anyMatch: Checks if any name starts with 'S'.

The program prints each name, names starting with 'S', concatenated names, the count of names, the first name, whether all names start with 'S', and whether any name starts with 'S'.

Real-World Use Cases of Java Streams

  • Streams are widely used in modern Java applications for:

    • Data Processing

    • For processing JSON/XML responses

    • For database Operations

    • Concurrent Processing

Important Points:

  • A stream consists of a source followed by zero or more intermediate methods combined together (pipelined) and a terminal method to process the objects obtained from the source as per the methods described.

  • Stream is used to compute elements as per the pipelined methods without altering the original value of the object.


Java 8 Optional Class

  • Java 8 added the Optional container class, which is used to express optional (nullable) items. By offering ways to properly handle and determine whether a value is present, it helps prevent NullPointerExceptions. We can define different values to return or different code to execute by using Optional. Because the developer can now see the previously hidden information, the code is easier to read.

Example: Java program without Optional Class

public class OptionalDemo {
    public static void main(String[] args)
    {
        String[] words = new String[10];
        String word = words[5].toLowerCase();
        System.out.print(word);
    }
}

Output

Exception in thread "main" java.lang.NullPointerException

To avoid abnormal termination, we use the Optional class. In the following example, we are using Optional. So, our program can execute without crashing.

Example: Program using Optional Class

import java.util.Optional;

// Driver Class
public class OptionalDemo {
      // Main Method
    public static void main(String[] args)
    {
        String[] words = new String[10];

          Optional<String> checkNull = Optional.ofNullable(words[5]);

          if (checkNull.isPresent()) {
            String word = words[5].toLowerCase();
            System.out.print(word);
        }
        else
            System.out.println("word is null");
    }
}

Output

word is null

Common Methods in Optional

  • Methods like isPresent(), orElse(), and ifPresent() are provided by the Optional class to handle potentially null values in a more secure and useful manner. Commonly used optional techniques are included in the table below along with descriptions.
MethodDescription
empty()Returns an empty Optional instance
of(T value)Returns an Optional with the specified present non-null value.
ofNullable(T value)Returns an Optional describing the specified value if non-null, else empty
equals(Object obj)Checks if another object is "equal to" this Optional.
filter(Predicate<? super T> predicate)If a value is present and matches the predicate, returns an Optional with the value; else returns empty.
flatMap(Function<? super T, Optional<U>> mapper)If a value is present, applies a mapping function that returns an Optional; otherwise returns empty.
get()Returns the value if present, else throws NoSuchElementException.
hashCode()Returns the hash code of the value if present, otherwise returns 0.
ifPresent(Consumer<? super T> consumer)Returns true if a value is present, else false.
map(Function<? super T, ? extends U> mapper)If a value is present, applies the mapping function and returns an Optional describing the result (if non-null).
orElse(T other)Returns the value if present, otherwise returns the provided default value.
orElseGet(Supplier<? extends T> other)Returns the value if present, otherwise invokes the supplier and returns its result.
orElseThrow(Supplier<? extends X> exceptionSupplier)Returns the value if present, otherwise throws an exception provided by the supplier
toString()Returns a non-empty string representation of this Optional for debugging.

Example 1 : Java program to illustrate some optional class methods.

import java.util.Optional;

class Main {

    // Driver code
    public static void main(String[] args)
    {

        // creating a string array
        String[] str = new String[5];

        // Setting value for 2nd index
        str[2] = "Advance Java";

        // It returns an empty instance of Optional class
        Optional<String> empty = Optional.empty();
        System.out.println(empty);

        // It returns a non-empty Optional
        Optional<String> value = Optional.of(str[2]);
        System.out.println(value);
    }
}

Output

Optional.empty
Optional[Advance Java]

Example 2 : Java program to illustrate some optional class methods

import java.util.Optional;

class Main {

    // Driver code
    public static void main(String[] args)
    {

        // creating a string array
        String[] str = new String[5];

        // Setting value for 2nd index
        str[2] = "Advance Java";

        // It returns a non-empty Optional
        Optional<String> value = Optional.of(str[2]);

        // It returns value of an Optional.If value is not present, it throws an NoSuchElementException
        System.out.println(value.get());

        // It returns hashCode of the value
        System.out.println(value.hashCode());

        // It returns true if value is present, otherwise false
        System.out.println(value.isPresent());
    }
}

Output

Advance Java
1967487235
true

Employee Data Analyzer Project in Java

  • We can handle and analyze employee data, including names, departments, and wages, in an effective and well-organized manner with Java's employee data analyzer system. Important Java concepts like handling exceptions, multithreading, object-oriented programming, and data manipulation are all taught to us through this project.

Before moving further, let's first understand how this system is going to work.

Working of Employee Data Analyzer

  • First, we will declare an Employee class which represents the employee's details like ID, name, departement, and salary.

  • We define EmployeeManager class, which will manage employee data by adding, retrieving, filtering, and sorting employee details.

  • We will use the most important concept which is multithreading in Java, it is used to make the system more efficient and to process employee data concurrently. Each employee's data will be processed in separate threads.

  • We’ll also implement error handling using custom exceptions, so that we can properly handle cases where an employee's data is not found.

Now, let's explore the structure of our system and the key components of the project

Project Structure

Project-Structure

  • We have organized the project into the following components:

    • Employee.java: This class holds the details of an employee.

    • EmployeeManager.java: This class is responsible for managing the employee data, including adding, fetching, filtering, and sorting employees.

    • EmployeeProcessor.java: This class process employee data in a separate thread.

    • EmployeeNotFoundException.java: A custom exception that will be thrown when an employee is not found in the system.

    • EmployeeDataAnalyzer.java: This is the main class that handles everything together and shows how the system works together.

Java Employee Data Analyzer Project Implementation

1. Employee.java:

  • This class is used to represent an employee. Each employee has an ID, a name, a department, and a salary. The salary is wrapped in an Optional to handle cases where the salary might be missing.
import java.util.Optional;

public class Employee {
    private int id;
    private String name;
    private String department;
    private Double salary;

    public Employee(int id, String name, String department, Double salary) {
        this.id = id;
        this.name = name;
        this.department = department;
        this.salary = salary;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getDepartment() {
        return department;
    }

    public Optional<Double> getSalary() {
        return Optional.ofNullable(salary);
    }

    @Override
    public String toString() {
        return "Employee{id=" + id + ", name='" + name + "', department='" + department + "', salary=" + salary + '}';
    }
}

Explanation:

  • Contains private fields: id, name, department, salary.

  • Constructoris used to initializes the fields.

  • Getter methods return field values.

  • getSalary() uses Optional.ofNullable() to safely handle null salary values.

  • toString() is overridden for clean object output (used in System.out.println())

2. EmployeeManager.java:

  • This class is used to handle employee data. It allows us to add employees, retrieve them by ID, filter employees based on salary, and sort employees by salary.
import java.util.*;
import java.util.stream.Collectors;

public class EmployeeManager {
    private Map<Integer, Employee> employeeData;

    public EmployeeManager() {
        this.employeeData = new HashMap<>();
    }

    public void addEmployee(Employee employee) {
        employeeData.put(employee.getId(), employee);
    }

    public Optional<Employee> getEmployeeById(int id) {
        return Optional.ofNullable(employeeData.get(id));
    }

    public List<Employee> getAllEmployees() {
        return new ArrayList<>(employeeData.values());
    }

    public List<Employee> filterEmployeesBySalary(Double minSalary) {
        return employeeData.values().stream()
                .filter(employee -> employee.getSalary().orElse(0.0) >= minSalary)
                .collect(Collectors.toList());
    }

    public List<Employee> sortEmployeesBySalary() {
        return employeeData.values().stream()
                .sorted(Comparator.comparingDouble(e -> e.getSalary().orElse(0.0)))
                .collect(Collectors.toList());
    }
}

Explanation:

  • employeeData is a HashMap<Integer, Employee> to store employees by ID.

  • addEmployee() method adds a new employee to the map.

  • getEmployeeById(int id) method safely returns an employee using Optional.

  • getAllEmployees() method returns a list of all employees.

  • filterEmployeesBySalary(Double minSalary) method filters employees whose salary ≥ minSalary using Stream.

  • sortEmployeesBySalary() method sorts all employees by their salary using Comparator

3. EmployeeProcessor.java:

  • To handle multiple employees at the same time, we use multithreading. The EmployeeProcessor class extends Thread to process employee data in parallel. If an employee doesn't exist, it will print a helpful error message.
import java.util.Optional;
public class EmployeeProcessor extends Thread {
    private EmployeeManager employeeManager;
    private int employeeId;

    public EmployeeProcessor(EmployeeManager employeeManager, int employeeId) {
        this.employeeManager = employeeManager;
        this.employeeId = employeeId;
    }

    @Override
    public void run() {
        try {
            Optional<Employee> employee = employeeManager.getEmployeeById(employeeId);
            employee.ifPresentOrElse(
                    emp -> System.out.println("Processing employee: " + emp),
                    () -> System.out.println("Employee with ID " + employeeId + " not found.")
            );
        } catch (Exception e) {
            System.out.println("Error processing employee data: " + e.getMessage());
        }
    }
}

Explanation:

  • EmployeeProcessor class takes an EmployeeManager and an employee ID as input.

  • Overrides run() to:

  • Fetch the employee by ID.

  • Use if PresentOrElse() to either print the employee or log not found.

  • Catch any exception to avoid thread crashes.

4. EmployeeNotFoundException.java:

  • This class defines a custom exception that will be thrown if an employee is not found in the system. This helps us handle missing employee records gracefully.
public class EmployeeNotFoundException extends Exception {
    public EmployeeNotFoundException(String message) {
        super(message);
    }
}

Explanation: A custom exception class for handling "employee not found" cases. Extends Exception and accepts a message in the constructor.

5. EmployeeDataAnalyzer.java:

  • This is the entry point of our system. It demonstrates how to add employees, process their data using threads, filter and sort employees, and handle errors. The main class uses EmployeeManager to manage employees and EmployeeProcessor to process them concurrently.
import java.util.List;

public class EmployeeDataAnalyzer {
    public static void main(String[] args) {
        EmployeeManager employeeManager = new EmployeeManager();

        // Adding employees to the system
        employeeManager.addEmployee(new Employee(1, "DOn", "Engineering", 75000.0));
        employeeManager.addEmployee(new Employee(2, "Bon", "Marketing", 68000.0));
        employeeManager.addEmployee(new Employee(3, "Fun", "Engineering", 80000.0));
        employeeManager.addEmployee(new Employee(4, "Keen", "HR", 55000.0));

        // Simulate multithreading: Processing employee by ID
        Thread processor1 = new EmployeeProcessor(employeeManager, 1);
        Thread processor2 = new EmployeeProcessor(employeeManager, 2);
        Thread processor3 = new EmployeeProcessor(employeeManager, 5);  // Non-existing employee

        processor1.start();
        processor2.start();
        processor3.start();

        // Wait for threads to complete
        try {
            processor1.join();
            processor2.join();
            processor3.join();
        } catch (InterruptedException e) {
            System.out.println("Error waiting for thread completion: " + e.getMessage());
        }

        // Filtering employees based on salary
        System.out.println("\nEmployees with salary >= 70000:");
        List<Employee> highEarners = employeeManager.filterEmployeesBySalary(70000.0);
        highEarners.forEach(System.out::println);

        // Sorting employees by salary
        System.out.println("\nEmployees sorted by salary:");
        List<Employee> sortedEmployees = employeeManager.sortEmployeesBySalary();
        sortedEmployees.forEach(System.out::println);
    }
}

Explanation:

  • This class is an entry point that drives the full application.

  • Creates an instance of EmployeeManager.

  • Adds four sample employees.

  • Creates and starts three threads (EmployeeProcessor) to simulate concurrent access.

  • Uses join() to ensure the main thread waits for all processors to finish.

  • Filters and prints employees with salary ≥ 70000.

  • Sorts and prints all employees by salary.

Output:

How to Run the project?

  • To run the project on IntelliJ IDEA we just need to follow these steps which are listed below:

    • Open IntelliJ IDEA and create a new Java project.

    • Start creating the packages and the structure must be look like this:

    • Employee.java

    • EmployeeManager.java

    • EmployeeProcessor.java

    • EmployeeNotFoundException.java

    • EmployeeDataAnalyzer.java

    • Create the classes and interface in the correct packages

    • Save all the files.

    • Run the main class


Happy Learning

Thanks For Reading! :)

SriParthu 💝💥

0
Subscribe to my newsletter

Read articles from sri parthu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

sri parthu
sri parthu

Hello! I'm Sri Parthu! 🌟 I'm aiming to be a DevOps & Cloud enthusiast 🚀 Currently, I'm studying for a BA at Dr. Ambedkar Open University 📚 I really love changing how IT works to make it better 💡 Let's connect and learn together! 🌈👋