Java tutorial
//package com.java2s; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.function.Function; public class Main { public static <K, V> Map<K, Collection<V>> toMap(final Collection<? extends V> items, final Function<V, K> mapper) { Map<K, Collection<V>> buffer = new HashMap<K, Collection<V>>(); // TODO this isn't probably thread-safe items.stream().forEach(item -> { K key = mapper.apply(item); Collection<V> c = buffer.getOrDefault(key, new ArrayList<V>()); c.add(item); buffer.put(key, c); }); return buffer; } }