Sobes.tech
Junior — Middle

What is the difference between the Stream and Iterable interfaces in Java?

sobes.tech AI

Answer from AI

In Java, the interfaces Stream and Iterable are used for working with collections but have different concepts and capabilities:

  • Iterable is a basic interface that provides the ability to obtain an iterator for sequential traversal of collection elements. Its iterator() method returns an Iterator object, which allows traversing the elements one by one.

  • Stream is a more modern interface introduced in Java 8 that supports a functional style of data processing. Streams enable filtering, transformation, aggregation, and other operations, often lazily and efficiently.

Main differences:

  • Element traversal: Iterable provides a simple way to sequentially traverse, while Stream is a more powerful tool for data processing with chainable operations.

  • Reusability: Iterable can be used multiple times, obtaining a new iterator each time. Stream becomes closed after use and cannot be reused.

  • Laziness: operations on Stream are usually lazy, meaning they are computed only when necessary (e.g., during a terminal operation).

  • Parallelism: Stream supports parallel data processing, simplifying the writing of multithreaded code.

Example of using Iterable:

Iterable<String> iterable = List.of("a", "b", "c");
for (String s : iterable) {
    System.out.println(s);
}

Example of using Stream:

Stream<String> stream = Stream.of("a", "b", "c");
stream.filter(s -> s.equals("b")).forEach(System.out::println);

Thus, Iterable is a basic interface for traversal, while Stream is a powerful tool for functional collection processing.

What is the difference between the Stream and… - sobes.tech