Skip to content
Elixir

Enum and Stream Operations

Functional collection operations in Elixir.

By EZ4Code Team
enumstreamfunctional

Code

# Map / Filter / Reduce
[1, 2, 3, 4, 5]
|> Enum.map(fn x -> x * x end)         # [1, 4, 9, 16, 25]
|> Enum.filter(fn x -> x > 5 end)      # [9, 16, 25]
|> Enum.reduce(0, fn x, acc -> acc + x end)  # 50

# Common operations
Enum.sum(1..100)                    # 5050
Enum.count([1, 2, 3, 4])           # 4
Enum.min_max([3, 1, 4, 1, 5])      # {1, 5}
Enum.uniq([1, 1, 2, 2, 3])         # [1, 2, 3]
Enum.sort([3, 1, 2])               # [1, 2, 3]
Enum.chunk_every([1,2,3,4,5], 2)   # [[1, 2], [3, 4], [5]]

# Find / any? / all?
Enum.find([1, 2, 3], fn x -> x > 2 end)        # 3
Enum.any?([1, 2, 3], fn x -> x > 2 end)        # true
Enum.all?([1, 2, 3], fn x -> x > 0 end)        # true

# Group / partition
Enum.group_by(["a", "bb", "c", "dd"], &String.length/1)
# %{1 => ["a", "c"], 2 => ["bb", "dd"]}

Enum.partition([1, 2, 3, 4, 5], fn x -> x > 2 end)
# {[3, 4, 5], [1, 2]}

# Comprehension
for x <- 1..3, y <- 1..3, x <= y, do: {x, y}
# [{1, 1}, {1, 2}, {1, 3}, {2, 2}, {2, 3}, {3, 3}]

Explanation

Enum is eager (materializes intermediate lists); Stream is lazy (computes on demand). Use Enum for most cases; switch to Stream for pipelines on large data. Comprehensions (for) are a concise alternative to map/filter combos. group_by, partition, chunk_every are powerful reshaping tools. Capture operator (&String.length/1) creates function shortcuts.

More Elixir Snippets