Parallel Streams

Parallel Streams#

TODO: Add this to Practice_Streams

    // let map be Map<String, Integer>.
    // Use streams to output the keys that have an even value, 
    // sort by the keys, case-insensitive.
    // output using `forEach` and a Method Reference to println.
    List<String> result = map.entrySet().stream()
        .filter(entry -> entry.getValue() % 2 == 0) // keep even values
        .sorted(Comparator.comparing(entry -> entry.getKey().toLowerCase())) // sort by key, case-insensitive
        .map(Map.Entry::getKey) // extract keys only
        .collect(Collectors.toList());

    result.forEach(System.out::println);

What is a Stream?#

A Stream is a sequence of elements processed in a functional style.

Key Characteristics of Streams

  1. Not a Data Structure: Unlike collections (e.g., List, Set), a Stream does not store elements. Instead, it provides a way to process elements from a source.

  2. Lazy Evaluation: Stream operations are performed lazily, meaning they are not executed until a terminal operation (like collect, forEach, or reduce) is invoked.

  3. Functional Style: Streams rely on functional-style operations, such as filter, map, and reduce, which can be chained together to form a pipeline of operations.

  4. Parallel Processing: Streams can be processed in parallel, making it easier to write parallel code and improve performance.