Data transformation with Streams

Input/Output and Streams in Java

Alex Liu

Software Development Engineer

Data transformation with streams

  • Data transformation with streams

    • Convert data formats, aggregate and filter information
    • Store results in new data collection type(eg. from List to Set)
    • 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 Stream to transform elements

  • Preparation: import required class Set, Collectors and Stream
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

// Convert the `ArrayList` we created earlier `names` to a `Stream` Stream<String> namesStream = names.stream();
  • Current data: [Alice, Bob, Charlie, David]
Input/Output and Streams in Java

Using Stream to transform elements (Continued)

// Use `.map()` to convert each element to upper case
Stream<String> upperCaseNameStream = namesStream.map(
        name -> name.toUpperCase())
  • Current data: [ALICE, BOB, CHARLIE, DAVID]
// use `.collect()` and `Collectors.toSet()` to store the transformed stream data in a `set`
upperCaseNameStream.collect(Collectors.toSet())
  • Final data:
    {CHARLIE, ALICE, BOB, DAVID}
    
Input/Output and Streams in Java

Using Stream for aggregation

  • The .reduce() method

    • Aggregates elements into a single result
    • Useful for summation, concatenation, or finding min/max
  • Use .reduce() takes two inputs

    • Initial Value: the starting value for the accumulation, e.g., 0
    • Binary Operator: A function that takes two arguments
      • (x, y) -> x + y means:
        • x represents the accumulated total
        • y represents the current element being processed
        • The operation adds y to x, continuing until all elements are processed
Input/Output and Streams in Java

Using Stream for aggregation: Example

  • Convert the ArrayList names to a Stream object.
    Stream<String> stream = names.stream();
    
  • Use .map() to convert name to its length and use .reduce() to add them up together
    stream
      .map(name -> name.length())
      .reduce(0, (sum, length) -> sum + length);
    
  • Result: 20
Input/Output and Streams in Java

Let's practice!

Input/Output and Streams in Java

Preparing Video For Download...