Sobes.tech
Junior — Middle

What are the differences between Stream and Collection interfaces in Java, and in which scenarios are their applications justified?

sobes.tech AI

Answer from AI

The Collection interface in Java represents a data structure — a container that stores elements. It defines methods for adding, removing, searching for elements, etc. Examples of implementations include ArrayList, HashSet, LinkedList. Collection is specifically a data storage.

The Stream interface is an abstraction for sequential data processing, allowing filtering, transformation, aggregation, etc. Streams do not store data but work with it "on the fly," support lazy computations, and can be sequential or parallel.

When to use:

  • If you just need to store and manage a set of elements — use Collection.
  • If you need to perform a chain of operations on data (filtering, sorting, mapping) — use Stream.

Example:

List<String> names = Arrays.asList("Anna", "Bob", "Charlie");
// Collection stores data

// Stream for data processing
List<String> filtered = names.stream()
    .filter(name -> name.startsWith("A"))
    .collect(Collectors.toList());
What are the differences between Stream and… - sobes.tech