Java tutorial
//package com.java2s; import java.lang.reflect.Field; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class Main { public static <K, V> Map<K, V> listToMap(List<V> list, String key) { return collectionToMap(list, key); } public static <K, V> Map<K, V> collectionToMap(Collection<V> collection, String key) { Map<K, V> map = null; Iterator<V> iterator = collection.iterator(); try { if (key == null) throw new Exception("no key filed"); else { map = new HashMap<K, V>(); while (iterator.hasNext()) { V v = iterator.next(); Class<? extends Object> c = v.getClass(); Field field = c.getField(key); field.setAccessible(true); map.put((K) field.get(v), v); } } } catch (Exception e) { e.printStackTrace(); } return map; } }