# Functional-style operations using Streams¶

Jivago provides a Stream class which can be used to perform functional-style operations on collections. This mechanism is heavily inspired by Java’s identically named Streams.

from jivago.lang.stream import Stream

# Result : [4, 16, 36]
square_of_even_numbers = Stream([1, 2, 3, 4, 5, 6]) \
.filter(lambda x: x % 2 == 0) \
.map(lambda x: x ** 2) \
.toList()


In the previous example, the usual filter and map operations are used in a sequential manner. While all these operations are all available in Python, using Jivago’s Streams allows the chaining of these operations to improve readability.

All available functions are documented in jivago.lang.stream.

## Wrapping None values using Nullables¶

Jivago provides Nullable objects which are used to wrap None items. This class follows the same structure as Java’s Optional class. Terminal Stream operations which return a single item use this mechanism.

All available functions are documented in jivago.lang.nullable.

## Other examples¶

from jivago.lang.stream import Stream

first_ten_square_numbers = Stream.range() \
.map(lambda x: x ** 2) \
.take(10)
# [1, 4, 9, 16, 25, ...]

Stream.zip(['a', 'b', 'c'], [1, 2, 3]) \
.forEach(lambda letter, number: print(f"{letter} is the {number}th letter of the alphabet."))

Stream.of(1, 2, 3, 4).allMatch(lambda x: x < 10)
# True

def square(x: int) -> int:
return x ** 2

squares = Stream.of(1, 2, 3, 4).map(square).toList()
# [1, 4, 9, 16]

alphabet = Stream([(1, 'a'), (2, 'b'), (3, 'c')]).toDict()
# { 1 : 'a', ...}