Junior — Middle
What are the main types of operations that can be performed with data streams in Java?
sobes.tech AI
Answer from AI
In Java, with data streams (Streams), the following main types of operations can be performed:
-
Intermediate operations — return a new stream and allow chaining:
filter— filtering elements based on a conditionmap— transforming elementsflatMap— transforming with unpacking of nested structuresdistinct— removing duplicatessorted— sorting elementslimitandskip— limiting and skipping elements
-
Terminal operations — complete the processing and return a result:
forEach— perform an action for each elementcollect— collect elements into a collection or other structurereduce— fold elements into a single valuecount— count the number of elementsanyMatch,allMatch,noneMatch— check conditionsfindFirst,findAny— find elements
Example:
List<String> names = Arrays.asList("Anna", "Bob", "Charlie", "David");
List<String> filtered = names.stream()
.filter(name -> name.length() > 3)
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());
Here, we filter names longer than 3 characters, convert them to uppercase, sort, and collect into a list.