package mahesh.core.util;
import mahesh.core.util.vo.Dimension;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
/**
* @author Maheshkumarp
* @version 1.0
* Date: Jul 29, 2009 - Time: 10:05:22 AM
*/
public class ListUtils<K> {
public static String camelHump(String str) {
if(str != null && (str = str.trim()).length() > 0) {
str = str.substring(0, 1).toUpperCase() + str.substring(1);
}
return str;
}
public static String convertFieldToAccessor(String filed) {
return "get" + camelHump(filed);
}
public <V> Map<K, V> toMap(List<V> list, String keyField) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
String accessor = convertFieldToAccessor(keyField);
Map<K, V> map = new HashMap<K, V>();
for(V obj : list) {
Method method = obj.getClass().getDeclaredMethod(accessor);
K key = (K)method.invoke(obj);
map.put(key, obj);
}
return map;
}
public static void main(String[] args) throws Exception {
List<Dimension> dimensionList = new ArrayList<Dimension>();
dimensionList.add(new Dimension(1, 2));
dimensionList.add(new Dimension(2, 2));
dimensionList.add(new Dimension(3, 223));
dimensionList.add(new Dimension(4, 2));
Map<Long, Dimension> dimensionMap = new ListUtils<Long>().toMap(dimensionList, "x");
System.out.println(dimensionMap);
}
}