Elixir Enum and Stream — Lazy and Eager Collection Operations
DodaTech
Updated 2026-06-29
1 min read
In this tutorial, you will learn about Elixir Enum and Stream. We cover key concepts, practical examples, and best practices to help you master this topic.
Elixir provides two modules for working with collections: Enum for eager operations (returns a new collection immediately) and Stream for lazy operations (computes values on demand). Knowing when to use each is key to writing efficient code.
In this tutorial, you'll master both Elixir modules for collection processing.
Enum
# Enum operations are eager — they return a new collection immediately
list = [1, 2, 3, 4, 5]
Enum.map(list, fn x -> x * 2 end) # => [2, 4, 6, 8, 10]
Enum.filter(list, fn x -> rem(x, 2) == 0 end) # => [2, 4]
Enum.reduce(list, 0, fn x, acc -> x + acc end) # => 15
# With pipe operator
list
|> Enum.map(&(&1 * 2))
|> Enum.filter(&(&1 > 5))
|> Enum.sum() # => 14 (6 + 8 + 10)
# Other useful Enum functions
Enum.min_max([3, 1, 4, 1, 5]) # => {1, 5}
Enum.group_by(["a", "bb", "ccc"], &String.length/1) # %{1 => ["a"], 2 => ["bb"], 3 => ["ccc"]}
Enum.chunk_every([1,2,3,4,5], 2) # => [[1,2], [3,4], [5]]
Enum.zip([1,2,3], [:a,:b,:c]) # => [{1,:a}, {2,:b}, {3,:c}]
Stream — Lazy Evaluation
# Stream creates a lazy pipeline — nothing computed until consumed
stream = 1..100_000
|> Stream.map(&(&1 * 2))
|> Stream.filter(&(rem(&1, 3) == 0))
|> Stream.take(5)
result = Enum.to_list(stream) # => [6, 12, 18, 24, 30]
# Only 5 values computed, not 100,000!
# Infinite streams
natural_numbers = Stream.iterate(1, &(&1 + 1))
first_ten = Enum.take(natural_numbers, 10) # => [1,2,3,4,5,6,7,8,9,10]
# Fibonacci via Stream
fib = Stream.unfold({0, 1}, fn {a, b} -> {a, {b, a + b}} end)
Enum.take(fib, 10) # => [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
# Stream.cycle
Stream.cycle(["a", "b", "c"]) |> Enum.take(7) # => ["a","b","c","a","b","c","a"]
When to Use Which
# Use Enum when:
# - Collection is small
# - You need all results immediately
# - Combining results from multiple pipelines
# Use Stream when:
# - Collection is large (not all values needed)
# - Processing infinite sequences
# - Chaining many operations
# - I/O operations (file streams)
← Previous
Elixir Functions — Named Functions, Anonymous Functions, and Captures
Next →
Elixir Pipe Operator — Data Transformation Pipelines
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro