Sobes.tech
Junior — Middle

Can you list the main categories of methods used in the Stream API?

sobes.tech AI

Answer from AI

In Java Stream API, the main categories of methods can be divided into three groups:

  1. Intermediate operations:

    • Return a new Stream, allowing chaining of operations.
    • Examples: filter(), map(), flatMap(), distinct(), sorted(), limit(), skip().
  2. Terminal operations:

    • End the chain and return a result (not a Stream).
    • Examples: forEach(), collect(), reduce(), count(), anyMatch(), allMatch(), noneMatch(), findFirst(), findAny().
  3. Stream creation operations:

    • Methods for creating streams from collections, arrays, values.
    • Examples: Stream.of(), Collection.stream(), Arrays.stream().

Example usage:

List<String> names = Arrays.asList("Anna", "Bob", "Charlie", "David");

long count = names.stream() // creating a Stream
    .filter(name -> name.length() > 3) // intermediate operation
    .count(); // terminal operation

System.out.println(count); // Outputs the number of names longer than 3

Thus, the main categories of Stream API methods are creation operations, intermediate operations, and terminal operations.

Can you list the main categories of methods used in… - sobes.tech