Java tutorial
//package com.java2s; import java.lang.reflect.Method; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class Main { /** * Creates a map with the elements of the collection as values using the * specified keyMethod to obtain the key from the elements. */ @SuppressWarnings("unchecked") public static <K, T> Map<K, T> createMap(Collection<T> collection, String keyMethod) { Map<K, T> map = new HashMap<>(collection.size()); if (collection.isEmpty()) { return map; } Class<?> elementClass = collection.iterator().next().getClass(); Method getKeyMethod; try { getKeyMethod = elementClass.getMethod(keyMethod, new Class[0]); } catch (Exception e) { throw new RuntimeException("Failed to get key method", e); } for (T element : collection) { K key; try { key = (K) getKeyMethod.invoke(element, (Object[]) null); } catch (Exception e) { throw new RuntimeException("Failed to get key", e); } map.put(key, element); } return map; } }