Junior — Middle
Can you list the types of operations that can be performed with streams?
sobes.tech AI
Answer from AI
In Java Stream API, operations are divided into intermediate and terminal.
Intermediate operations return a new Stream and allow building a data processing pipeline:
filter(Predicate)— filtering elementsmap(Function)— transforming elementsflatMap(Function)— transforming with unwrapping nested streamsdistinct()— removing duplicatessorted()andsorted(Comparator)— sortinglimit(long)— limiting the number of elementsskip(long)— skipping the first elements
Terminal operations complete the processing and return a result or a side effect:
forEach(Consumer)— performing an action for each elementcollect(Collector)— collecting elements into a collection or other structurereduce(BinaryOperator)— folding elements into a single valuecount()— counting elementsanyMatch(Predicate),allMatch(Predicate),noneMatch(Predicate)— condition checksfindFirst(),findAny()— finding an element
Example:
List<String> names = Arrays.asList("Anna", "Bob", "Alice", "Brian");
List<String> filtered = names.stream()
.filter(s -> s.startsWith("A"))
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());
// filtered = ["ALICE", "ANNA"]