Logo

Programming-Idioms

# 335 List to map
Create the map m containing all the elements e of the list a, using as key the field e.id.
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
final m = {
  for (final e in a) e.id: e,
};
m := make(map[K]V, len(a))
for _, e := range a {
	m[e.id] = e
}
import java.util.HashMap;
import java.util.List;
import java.util.Map;
static class Id {}
record Element(Id id) {}
@SuppressWarnings("unchecked")
<K extends Id, V extends Element> Map<K, V> map(List<V> a) {
    Map<K, V> m = new HashMap<>();
    for (V e : a) m.put((K) e.id(), e);
    return m;
}
local m={}
for _,e in ipairs(a) do
 m[e.id]=e
end
foreach my $e (@a) {
    $m{$e->id) = $e;
}
m = {e.id:e for e in a}
m = a.group_by(&:id)
use std::collections::HashMap;
let mut m = HashMap::new();

for e in a {
	m.entry(e.id).or_insert_with(Vec::new).push(e);
}