Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #335 List to map

Create the map m containing all the elements e of the list a, using as key the field e.id.

m := make(map[K]V, len(a))
for _, e := range a {
	m[e.id] = e
}
final m = {
  for (final e in a) e.id: e,
};
import java.util.HashMap;
import java.util.Map;
Map<Integer, E> m = new HashMap<>();
a.forEach(e -> m.put(e.id, e));
import java.util.Map;
Map<Integer, E> m = a.stream()
    .collect(toMap(e -> e.id, e -> e));
import java.util.HashMap;
import java.util.Map;
Map<Integer, E> m = new HashMap<>();
for (E e : a) m.put(e.id, e);
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}
f = lambda x: (x.id, x)
m = dict(map(f, 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);
}

New implementation...
< >
programming-idioms.org