# 将一个`List`转换成一个`HashMap`的方法

利用JAVA streamAPI

```java
Map map = permissionList.stream()
.collect(Collectors.toMap(obj-> obj.getId(), obj-> obj));

```

```

```

-----------------以下过期-------------

~~分两种情况~~

1. ~~O.成员为可访问,使用`obj.getClass().getDeclaredField(indexName)`。~~
2. ~~O.成员为不可访问,需要编写O.get成员方法,使用`obj.getClass().getMethod("get" + toUpperCase(indexName), null).invoke(obj)`。~~

```java
public static HashMap
listToHashMap(String indexName, List list) throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
HashMap map = new HashMap<>(list.size());
for (O obj : list) {
Field field = obj.getClass().getDeclaredField(indexName);
try {
map.put((K) field.get(obj), obj);
} catch (IllegalAccessException e) {
K key = (K) obj.getClass().getMethod("get" + toUpperCase(indexName), null).invoke(obj);
map.put(key, obj);
}
}
return map;
}

public static String toUpperCase(String str) {
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
```

Last modification:October 16, 2022
如果觉得我的文章对你有用,请随意赞赏