rrrr

rrrr

How to "merge" / "map" two sparse maps into one?

What is Elixir way to “merge” / “map” two sparse maps onto one? I want to apply some function on both or single value from these maps. By “sparse” i mean that some keys are missing in another map. Like
a = %{1=>1, 2=>2, 4=>4}
b = %{0=>0, 1=>11, 2=>22, 5=>55}
looking for c=%{0=>f(0), 1=>f(1,11), …}

So far I have come with obtaining list of common keys and moving with it as index for both maps.

Closest built-in solution was Map.merge(map1, map2, fun), but it does not cover custom behavior when key is missing in one map.

Can solution be Stream’able?
Should I look for some non-default library?

Marked As Solved

LostKobrakai

LostKobrakai

Map.new(Map.keys(a) ++ Map.keys(b), fn key -> 
  case {Map.fetch(a, key), Map.fetch(b, key)} do
    {:error, {:ok, val}} -> {key, f(val)}
    {{:ok, val}, :error} -> {key, f(val)}
    {{:ok, val_a}, {:ok, val_b}} -> {key, f(val_a, val_b)}
    # {:error, :error} not possible
  end
end)

Also Liked

Sorc96

Sorc96

Can you merge the maps first and then apply the function?

Map.merge(a, b, fn _key, value1, value2 -> {value1, value2} end)
|> Map.new(fn
  {key, {value1, value2}} -> {key, f(value1, value2)}
  {key, value} -> {key, f(value)}
end)

It could get a bit cleaner if Elixir had an equivalent of Ruby’s transform_values, then it wouldn’t be necessary to repeat the key manually.

I’m guessing you want to use Stream because of t hef function? In that case I think you could first use Stream.map and then convert the result back into a map.

hlx

hlx

map1 = %{a: 1, b: 2}
map2 = %{b: 1, c: 1}
fun = fn x, y -> x + y end

for {k1, v1} <- map1, {k2, v2} <- map2, reduce: %{} do
  acc ->
    if k1 == k2 do
      Map.put(acc, k1, fun.(v1, v2))
    else
      acc
      |> Map.put(k1, v1)
      |> Map.put(k2, v2)
    end
end

edit: after reviewing it myself this is not a great solution.

LostKobrakai

LostKobrakai

This one iterates map2 for each key/value pair in map1. That can become expensive rather quickly.

Last Post!

codeanpeace

codeanpeace

I like how the case statement makes this approach very readable.

Just wanted to add that, depending on how often both maps contain overlapping keys, it could make sense to manually remove duplicated keys e.g. Map.keys(a) ++ Map.keys(b) |> Enum.uniq.

Map.new/2 already removes duplicated keys with the latest one prevailing. But that means it would unnecessarily run through the case statement twice whenever a key exists in both maps.

Where Next?

Trending in Questions Top

lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
tj0
I’ve been following the steps here for the upgrade from 1.6 to 1.7 and it has gone relatively smoothly all the way till the phoenix_view ...
New
cgraham
Hi! What is currently the best library/method for parsing text and tabular data out of PDF files in Elixir or Erlang?
New
stefanchrobot
Hi, I need a way to handle data migrations in my application. I found an article by @wojtekmach about manual migrations: Automatic and ma...
New
stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
kip
Localize is the next generation localisation library for Elixir. Think of it as ex_cldr version 3.0. The first version will be released ...
New
webofbits
Squid Mesh is an open source workflow automation runtime for Elixir applications. It is aimed at Phoenix and OTP apps that want to defin...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
kip
In 2021 I started a new library called Tempo with the objective of modelling time as a set of intervals - not as instants. In 2022 I gave...
New

We're in Beta

About us Mission Statement