Consumer
Performs an operation on an object.
Typically used to perform a common operation on all items in a Collection
or Stream
, or on the value which may be contained in an Optional
. (It can be useful to view Collection
.forEach(
Consumer
)
as an “inside-out” variation on the enhanced-for.)
Parameterized by the type contained in the Collection
, Stream
, Optional
, etc.
Method to be implemented is void accept(T t)
. Thus, a lambda that implements Consumer
must take a single parameter and return no result. (If an expression lambda is used, the evaluated result—if any—will be ignored.)
Collection
using Collection
.forEach(
Consumer
)
:List.of(1, 1, 2, 3, 5, 8, 13)
.forEach(System.out::println); // Print each value.
Stream
using Stream
.forEach(
Consumer
)
:Stream.of(1, 1, 2, 3, 5, 8, 13)
.forEach(System.out::println); // Print each value.
Both of above examples produce this output:
1
1
2
3
5
8
13