Sobes.tech
Junior

What is the difference between stateful and stateless operations in streams? Provide examples.

sobes.tech AI

Answer from AI

In the context of streams (for example, in Dart or Java Streams), operations are divided into stateful and stateless depending on whether they require maintaining state to process elements.

  • Stateless operations do not depend on previous elements and process each element independently. They do not store intermediate state. Examples: map, filter, forEach.

  • Stateful operations require storing some state to process the current element. For example, operations that depend on order or require aggregation. Examples: distinct (need to remember already seen elements), sorted (need to keep all elements for sorting), skip, limit.

Example in Dart:

var numbers = [1, 2, 2, 3, 4];

// Stateless: map - each element is multiplied by 2 independently
var doubled = numbers.map((n) => n * 2);

// Stateful: distinct - need to remember which elements have already been seen
var unique = numbers.toSet();

print(doubled.toList()); // [2, 4, 4, 6, 8]
print(unique.toList());  // [1, 2, 3, 4]

Thus, stateless operations are simpler and more efficient as they do not require additional memory for state, whereas stateful operations can be more resource-intensive.