Junior
What is a Stream in Java?
sobes.tech AI
Answer from AI
A Stream in Java is a sequence of elements supporting sequential and parallel aggregate operations. It is not a data structure, but a view of data that allows for functional-style operations on collections of elements.
Main characteristics:
- Does not modify the source: A Stream does not modify the collection or array it was created from.
- Lazily evaluated: Intermediate operations like
filter,mapare not executed immediately. Execution begins only when a terminal operation such asforEach,collect, orsumis invoked. - Can be used only once: After a terminal operation, the Stream is considered closed and cannot be reused.
Main types of operations:
- Intermediate: Return a new Stream. Examples:
filter(),map(),sorted(),distinct(),limit(),skip(). - Terminal: Return a result or a side-effect and end the Stream pipeline. Examples:
forEach(),collect(),count(),sum(),average(),reduce(),min(),max(),anyMatch(),allMatch(),noneMatch().
Example usage:
// Creating a Stream from a list of strings
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
// Intermediate operation: filter names starting with 'A'
Stream<String> filteredNamesStream = names.stream()
.filter(name -> name.startsWith("A"));
// Intermediate operation: convert all names to uppercase
Stream<String> upperCaseNamesStream = filteredNamesStream
.map(String::toUpperCase);
// Terminal operation: print the filtered and transformed names
upperCaseNamesStream.forEach(System.out::println);
// Chained version:
names.stream()
.filter(name -> name.startsWith("A")) // Intermediate
.map(String::toUpperCase) // Intermediate
.forEach(System.out::println); // Terminal
Using the Stream API simplifies working with collections, making code more readable and efficient, especially when parallelized.