collect() and Collectors

Зачем это нужно

Modern Java code often processes collections of objects such as users, orders, products, and query results. Lambdas and the Stream API describe what should happen to data without mixing business rules with manual indexes and temporary variables. This makes code compact, but requires a clear understanding of types, operation order, and evaluation timing.

This article moves from the basic term to a practical pipeline. A lambda is not a standalone data type; it becomes a value of a specific functional interface. A Stream does not store elements and does not replace a Collection: it is a computation pipeline that reads a source and builds a result.

Java streams and lambdas

Термины

The key concepts are: toList, toSet, toMap, groupingBy, partitioningBy, joining.

When reading Stream code, find the source first, then intermediate operations, and finally the terminal operation. Intermediate operations usually return another Stream and are lazy. A terminal operation starts evaluation. A lambda defines a small rule: test, transform, consume, or create a value.

Пример

Map<Status, List<Order>> groups = orders.stream().collect(Collectors.groupingBy(Order::getStatus));

Run the example with a User or Order class. Change the condition and result type, then explain which interface receives the lambda. Notice that calling stream() alone does not execute the pipeline.

Таблица

Tool Purpose
Predicate Describes a test that returns boolean
Function Transforms one value into another
Consumer Performs an action without returning a value
Stream Lazy pipeline for processing elements
Collector Rule for assembling elements into a result

Как выбирать операцию

Use filter and Predicate when elements must be kept or rejected. Use map and Function when each element becomes another object. Use Consumer for an effect such as logging, but do not turn an entire pipeline into side effects. Use reduce for one combined value and collect for a collection or grouping.

A Stream does not mutate its source Collection. It describes a computation, and the terminal operation reads the source. Order matters: filtering before mapping can reduce work, sorting compares elements, and limit can stop reading in a suitable pipeline. Do not make a long chain unreadable; extract complex rules into a named method.

Практическая последовательность

  1. Choose a Collector.
  2. Define the result container.
  3. Group or partition the elements.
  4. Return the completed structure.

Итог

A lambda expresses a small rule, a functional interface defines its contract, and the Stream API composes those rules into a readable data-processing pipeline.

Glossary
bytecode
Platform-independent compiled code that the JVM can execute.
class
A blueprint that defines fields and methods for objects in object-oriented programming.
object
A runtime instance of a class with its own state and behavior.
method
A named block of behavior that belongs to a class or object and can be called by code.
field
A variable stored inside a class or object that represents part of its state.
constructor
A special method-like block used to create and initialize a new object.
package
A namespace that groups related Java classes and helps organize code.
interface
A contract that defines methods a class can implement without prescribing all internal details.
generics
A language feature that lets code work with types as parameters while preserving type safety.
type erasure
The Java compiler process that removes most generic type details from runtime bytecode.
collection
A data structure that stores a group of elements and provides operations over them.
list
An ordered collection where elements have positions and duplicates are allowed.
set
A collection that stores unique elements and is commonly used for membership checks.
map
A key-value data structure where each key points to a value.
queue
A collection designed for processing elements in a defined order, often first-in-first-out.
lambda
A compact function-like expression used to pass behavior as data.
functional interface
An interface with one abstract method, suitable for lambdas and method references.
stream
A Java API for processing data sequences with operations such as map, filter, and reduce.
optional
A container object that represents a value that may or may not be present.
thread
An independent path of execution inside a running program.
synchronization
Coordination that protects shared data when multiple threads access it.
heap
The runtime memory area where Java objects are allocated.
stack
The runtime memory area that stores method calls, local variables, and call frames.
garbage collector
A JVM component that automatically frees memory occupied by objects no longer reachable.
memory leak
A situation where memory remains occupied because objects are still referenced but no longer useful.