A stream terminal operation defines the returned result, while the source and intermediate operations define which elements can contribute to it.
Java stream reference: grouping, ordering and empty-result contracts
Java 8+. This is a complete program using JDK classes.
Choose the terminal result explicitly
Use collect for a result container with a defined accumulation policy. Use a reduction when an associative combining rule and neutral identity describe the result. Use an optional result when an empty source has no selected value; do not silently replace absence with a meaningful business number.
The program groups first-seen statuses in a LinkedHashMap and counts their occurrences. The merge function makes duplicate-key behavior explicit. Without a merging rule, toMap can reject duplicate keys instead of returning a count.
Preserving first-seen output order is a requirement of this sequential collector and supplied map. It is not proof that every parallel grouping or source has the same order. If consumers need a sorted report, choose a sorted key order or sort the finished entries.
Review before publishing a pipeline
Check source size, short-circuit behavior, operation state, exceptions, ownership of collected elements and the empty case. intermediate callbacks should not carry required external side effects. Closing a stream can matter when it owns a file or another resource, even though an ordinary list stream usually owns no such handle.
Working program
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class StatusGroupingReference {
public static void main(String[] args){
Map<String,Long> counts=Arrays.asList("paid","pending","paid").stream()
.collect(Collectors.toMap(Function.identity(),status->1L,Long::sum,LinkedHashMap::new));
System.out.println(counts);
System.out.println(Collections.<Integer>emptyList().stream().max(Integer::compare).isPresent());
}
}Output
{paid=2, pending=1}
falseCosts and boundaries
The grouping visits n statuses and stores k distinct keys. Hash-based insertion is typically constant expected work per status, while string hashing still reads characters. This is an in-memory result, not a streaming output with bounded key cardinality.
Common Mistakes
- A duplicate-key policy must be chosen for toMap.
- An empty maximum is absence, not automatically zero.
- A file-backed stream needs an owning close scope.
