Introduction to Streams

Input/Output and Streams in Java

Alex Liu

Software Development Engineer

Working with Streams

  • Java Streams

    • Process data collections functionally and Improve performance for large data
    • Supported Collections:
      • Lists (e.g. ArrayList, LinkedList)
      • Sets (e.g. HashSet, TreeSet)
      • Maps (Keys/Values as Streams) (e.g., HashMap, TreeMap)
      • Arrays (via Arrays.stream())
  • Example ArrayList named namesto use for the rest of the video

    names: ["Alice", "Bob", "Charlie", "David"]
    
Input/Output and Streams in Java

Using lambda expressions with Stream

  • Lambda Expressions
    • Syntax: (parameters) -> { expression }
names.forEach(
    // `name` is a parameter representing each element in the list
    name -> 
        // This is the expression executed for each element.
        System.out.println(name));
Alice 
Bob 
Charlie 
David
Input/Output and Streams in Java

Creating a Stream

  • Convert data collection to Stream

    • Use .stream() on a collection
    • Supports List, Set and Queue
  • Import Stream class

    import java.util.stream.Stream;
    
  • Converted sample list names to streams and use .foreach() to access each element.
    Stream<String> stream = names.stream();
    stream.forEach(name -> System.out.println(name));
    
Input/Output and Streams in Java

Filtering data with Streams

  • Use .filter() to select elements
    • Keeps only matching elements
  • Converted sample list names to streams
    Stream<String> stream = names.stream();
    
  • Use .filter() to match elements starts with A and use .forEach() to print them
    stream
      .filter(name -> name.startsWith("A"))
      .forEach(name -> System.out.println(name));
    
  • Filter result: Alice
Input/Output and Streams in Java

Counting elements with Streams

  • Use .count() to count elements

    • Returns value in long format
  • Converted sample list names to streams

    Stream<String> stream = names.stream();
    
  • Use .filter() to match elements starts with B and use .count() to count them

    long count = names.stream()
      .filter(name -> name.startsWith("B"))
      .count();
    
  • Count result: 1 (only 1 element Bob start with B)

Input/Output and Streams in Java

When to use Streams

  • When to Use Streams:
    • For large datasets: Reduces performance overhead
    • For functional operations: More readable than loops
    • For filtering and transformations: Simplifies code
  • When NOT to Use Streams:
    • For modifying original collections
    • For simple loops with side effects
Input/Output and Streams in Java

Let's practice!

Input/Output and Streams in Java

Preparing Video For Download...