Java tutorial
//package com.java2s; import java.lang.reflect.Method; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; public class Main { public static void putAllInHashMapByGivenAttribute(HashMap map, Collection col, String attribName) { Iterator iter = col.iterator(); while (iter.hasNext()) putInHashMapByGivenAttribute(map, iter.next(), attribName); } public static HashMap putAllInHashMapByGivenAttribute(Collection col, String attribName) { HashMap map = new HashMap(); putAllInHashMapByGivenAttribute(map, col, attribName); return map; } public static void putInHashMapByGivenAttribute(HashMap map, Object obj, String attribName) { try { Class class1 = obj.getClass(); String methodName = "get" + Character.toUpperCase(attribName.charAt(0)) + attribName.substring(1); Method method = class1.getMethod(methodName, new Class[0]); Object attributeValue = method.invoke(obj, new Object[0]); map.put(attributeValue, obj); } catch (Exception e) { e.printStackTrace(); } } }