Streams

Introduced in Java 8, Stream API is used to process collections.

Some of the most common functions of them are:

  • forEach
  • map
  • filter
  • allMatch
  • reduce

All of this functions accept lambda function which specifies what will be done to the iterated elements.

Lambda functions don't have any names and have the following syntax:

forEach

Iterates the elements of an List.

It accepts a function as an argument which has a single argument - the value of the iterated element.

Let's look at the following example:

Output:

The code snippet prints all values of the List in a way specified in the lambda function.

map

Returns stream which elements are modified in the lambda and can be converted to List.

Output:

In this case the modification is specified according to the returned value - value * 2.

.collect(Collectors.toList()) is used to convert the map function result into list.

If the lambda function returns a single expression it can be simplified.

From this:

To this:

Output:

filter

Allows filtering specific elements.

if the lambda returns true - the element will be present in the returned stream.

If the lambda returns false - it will not be present.

For example we can filter the List to return only the even numbers:

Output:

allMatch

Allows checking if all elements match certain condition.

If all of the elements match the condition in the lambda (to return true), then the allMatch function returns true.

If one or more of the elements don't match the condition in the lambda (to return false), then the allMatch function returns true.

For example we can check if all of the elements in the list are even:

Output:

reduce

Accumulates a single value based on a lambda function.

It has 2 arguments - the initial value and the lambda function.

The callback accepts 2 arguments - total and value in which total is the accumulated value.

An example of function summing List elements with System.out.println for explanations:

Output: