Diference betwen Enum.map and Stream.map

Can someone explain me the diference betwen Enum.map and Stream.map, because i have this piece of code:
File.stream!(path)
|> Stream.map(&parse_line_to_string/1)
|> Stream.filter(fn {status,_} -> status == “SP” or status == “RA” end)
|> Enum.map(&build_claim/1)

and it build the claims but if i replace Enum to Stream it doesn’t work.

i dont know how it’s work

Enum.map immediately maps over a collection. Stream.map on the other hand returns a value that describes how to map over a stream. This way we can lazy build a stream from operations such as map and filter and later decide to run it.

If you replace your Enum.map with Stream.map the stream will never be executed, instead the value describing how to map will just be returned.

1 Like

One way to think about it is that each Stream call is essentially writing a mini program on that step of the pipeline; those programs don’t get “compiled and run” until there is an Enum in the pipeline to start the execution.

If that way of thinking doesn’t help, then just ignore it.

1 Like

File.stream!(path)
|> Stream.map(&parse_line_to_string/1)
|> Stream.filter(fn {status,_} -> status == “SP” or status == “RA” end)
|> Stream.map(&build_claim/1)
|> Enum.each(&store_claim/1)

Thanks, for helping me, i was doing something after the stream, and i get the conclusion that you can use Stream intermedialy but at the finally you need to que all the collection for finish it

Please correct me if i am wrong.

1 Like

This is my understanding. A stream ‘waits’ until items are called by streaming it into an enumerable or calling Stream.run

1 Like