Sobes.tech
Junior — Middle

What are the main types of operations that can be performed with data streams in Java?

sobes.tech AI

Answer from AI

In Java, with data streams (Streams), the following main types of operations can be performed:

  1. Intermediate operations — return a new stream and allow chaining:

    • filter — filtering elements based on a condition
    • map — transforming elements
    • flatMap — transforming with unpacking of nested structures
    • distinct — removing duplicates
    • sorted — sorting elements
    • limit and skip — limiting and skipping elements
  2. Terminal operations — complete the processing and return a result:

    • forEach — perform an action for each element
    • collect — collect elements into a collection or other structure
    • reduce — fold elements into a single value
    • count — count the number of elements
    • anyMatch, allMatch, noneMatch — check conditions
    • findFirst, findAny — find elements

Example:

List<String> names = Arrays.asList("Anna", "Bob", "Charlie", "David");
List<String> filtered = names.stream()
    .filter(name -> name.length() > 3)
    .map(String::toUpperCase)
    .sorted()
    .collect(Collectors.toList());

Here, we filter names longer than 3 characters, convert them to uppercase, sort, and collect into a list.

What are the main types of operations that can be… - sobes.tech