Sobes.tech
Middle

What operations exist in streams and what types of operations are there?

sobes.tech AI

Answer from AI

In Java 8+ streams provide a set of operations for processing data collections.

Types of operations:

  1. Intermediate: Return a new stream. Can be performed lazily. Allow chaining of operations. They include:

    • filter()
    • map()
    • flatMap()
    • distinct()
    • sorted()
    • peek()
    • limit()
    • skip()
  2. Terminal: End the stream, perform processing, and return a result or produce a side effect. After a terminal operation, the stream cannot be reused. They include:

    • forEach()
    • forEachOrdered()
    • toArray()
    • reduce()
    • collect()
    • count()
    • sum()
    • average()
    • min()
    • max()
    • anyMatch()
    • allMatch()
    • noneMatch()
    • findFirst()
    • findAny()

Example of a chain of operations:

// Intermediate operations (filter, map)
// Terminal operation (collect)
List<String> filteredList = originalList.stream()
    .filter(s -> s.startsWith("A")) // Filtering elements starting with "A"
    .map(String::toUpperCase) // Transforming to uppercase
    .collect(Collectors.toList()); // Collecting results into a List