Currently i am using following code and my question is , is there a better way to do. i mean if there is more concise way, or may be a built-in function to do so.
While Enum.into is the simplest, You could have rewritten your Enum.reduce like this.
list = [[1, 5], [3, 12], [4, 10]]
Enum.reduce(list, %{}, fn [k, v], acc -> Map.put(acc, k, v) end)
# or the for version of it
for [k, v] <- list, reduce: %{} do acc -> Map.put(acc, k, v) end
I would not use Map.put or Enum.into because that means that the runtime copies the map, adds one more pair to it, then throws out the previous one – N times. That’s very inefficient.
Go with what @NobbZ suggested: it basically says “construct a new map using this list and then use this function (the second parameter, in this case List.to_tuple) to convert each element of the list to a key/value tuple” – which is the format that Map.new expects.
For (supposedly) even bigger efficiency I’d write this:
Map.new(your_list, fn [k, v] -> {k,v} end)
This has the added benefit that it will break if your list is malformed, namely you want a list of sublists and each of the sublists must be exactly 2 elements long. If there’s even one sublist that is not 2-sized then you’ll get a runtime error. Annoying, sure, but you’ll know you have a bug very quickly and can fix it.