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 anIteratorobject, 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:
Iterableprovides a simple way to sequentially traverse, whileStreamis a more powerful tool for data processing with chainable operations. -
Reusability:
Iterablecan be used multiple times, obtaining a new iterator each time.Streambecomes closed after use and cannot be reused. -
Laziness: operations on
Streamare usually lazy, meaning they are computed only when necessary (e.g., during a terminal operation). -
Parallelism:
Streamsupports 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.