list转map实列
时间: 2023-10-15 14:24:19 浏览: 83
List转换成Map工具类的简单实例
引用中提供了一个将List转为Map的方法。该方法接收一个实体类的列表和获取主键的方法名作为参数,返回一个Map<String, Object>。具体实现如下:
```java
public static Map<String, Object> listToMap(List<?> list, String getkey) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SecurityException {
Map<String, Object> map = new HashMap<String, Object>();
for (int i = 0; i < list.size(); i++) {
Class<?> cl = list.get(i).getClass();
Method m1 = cl.getDeclaredMethod(getkey);
String key = (String) m1.invoke(list.get(i));
map.put(key, list.get(i));
}
return map;
}
```
这个方法首先创建了一个空的HashMap用于存放转换后的数据。然后通过循环遍历列表中的每个实体对象。在每次循环中,首先获取当前实体对象的类对象和通过getkey方法获取的主键值。然后将主键值作为键,实体对象作为值,添加到HashMap中。最后返回转换后的Map对象。这样,就将List转换为Map实例了。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [【Scala】基础4:集合——List、Set和Map](https://blog.csdn.net/hr786250678/article/details/86360179)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *3* [将List转为Map 如List转为Map,javaBean>](https://blog.csdn.net/rongchengqingnian/article/details/51953501)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文