Sobes.tech
Junior — Middle

What happens when you call the stream() method on an ArrayList object?

sobes.tech AI

Answer from AI

Calling the stream() method on an ArrayList object in Java creates a sequential stream (Stream) of the list's elements. This stream allows performing data processing operations in a functional style, such as filtering, transforming, sorting, and aggregating.

For example:

ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");

list.stream()
    .filter(s -> s.startsWith("b"))
    .forEach(System.out::println); // Will output "banana"

It is important to note that calling stream() does not modify the original list but creates a new stream object for further operations. The stream is lazy, meaning operations on it are only executed during a terminal operation (e.g., forEach, collect).