List转Map任意类型KV,自定义key规则工具类
public static <K, V> Map<K, V> list2Map3(List<V> list, String keyMethodName,Class<V> c) {
Map<K, V> map = new HashMap<K, V>();
if (list != null) {
try {
Method methodGetKey = c.getMethod(keyMethodName);
for (int i = 0; i < list.size(); i++) {
V value = list.get(i);
@SuppressWarnings("unchecked")
K key = (K) methodGetKey.invoke(list.get(i));
map.put(key, value);
}
} catch (Exception e) {
throw new IllegalArgumentException("field can't match the key!");
}
}
return map;
}
转载记录:https://blog.csdn.net/cherishpart/article/details/52555218