Stream API in Java

Jul 11, 2024

Stream API in Java

Introduction

  • Previous video covered forEach and its usage.
  • Current topic: Stream API.
  • Purpose of collections in Java: To store data (integers, strings, complex objects).

Processing Data in Collections

  • Methods for processing data:
    • Normal for loop
    • External for loop
    • forEach
  • Operations needed:
    • Changing values
    • Filtering values
    • Reducing values

Stream API Overview

  • Allows for various operations without modifying the existing list.
  • Preferred for processing large amounts of data using multiple threads.

Creating a Stream

  • Convert a collection to a stream: nums.stream() or nums.parallelStream().
  • Streams allow for operations like map, filter, reduce etc.

Basic Stream Operations

  1. Mapping Values: Example - Doubling Values

    • Use the map method: data.map(n -> n * 2)
    • Creates a new stream without modifying the original list.
  2. ForEach

    • Iterate over stream values.
  3. Handling Streams

    • Streams can only be consumed once.
    • Example of handling exceptions when trying to reuse a consumed stream.

Stream Operations: Examples

  • Count: Get the size of the stream.
  • Sorted: Sort the values in the stream.
  • Filter: Filter values based on a condition (e.g., even/odd numbers).
    • Example: filter(n -> n % 2 == 1) for odd numbers.
  • Map: Transform each value (e.g., doubling values).
  • Reduce: Combine stream values into a single result.
    • Example: Summing values: reduce(0, (acc, elem) -> acc + elem)

Stream Method Details

  • Filter: Uses Predicate functional interface (filter(Predicate))
  • Map: Uses Function functional interface (map(Function))
  • Demonstration of using and replacing lambdas with full predicate or function objects.

Lambda Expressions

  • Simplify code syntax.
  • Reduction explanation: simplify down to a single concise operation.

Advanced Operations and Insights

  • Streams prevent data leakage and ensure resource management.
  • Methods to chain stream operations for readability and efficiency.
  • Explanation of building streams using builder pattern.
  • Combining multiple stream methods: stream().filter(...).map(...).forEach(...)

Conclusion

  • Stream API offers efficient and readable ways to process collections.
  • Benefits in large data processing with parallel streams.
  • Encouragement to explore more Stream API features.