in src/main/java/net/hydromatic/linq4j/EnumerableDefaults.java [1928:1956]
static <TSource, TKey, TElement> LookupImpl<TKey, TElement> toLookup_(
Map<TKey, List<TElement>> map, Enumerable<TSource> source,
Function1<TSource, TKey> keySelector,
Function1<TSource, TElement> elementSelector) {
final Enumerator<TSource> os = source.enumerator();
try {
while (os.moveNext()) {
TSource o = os.current();
final TKey key = keySelector.apply(o);
List<TElement> list = map.get(key);
if (list == null) {
// for first entry, use a singleton list to save space
list = Collections.singletonList(elementSelector.apply(o));
} else {
if (list.size() == 1) {
// when we go from 1 to 2 elements, switch to array list
TElement element = list.get(0);
list = new ArrayList<TElement>();
list.add(element);
}
list.add(elementSelector.apply(o));
}
map.put(key, list);
}
} finally {
os.close();
}
return new LookupImpl<TKey, TElement>(map);
}