如何将列表转换为地图? [英] How to convert List to Map?

查看:45
本文介绍了如何将列表转换为地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我与一位同事讨论了在 Java 中将 List 转换为 Map 的最佳方式是什么,以及这样做是否有任何具体好处.

我想知道最佳转换方法,如果有人能指导我,我将不胜感激.

这是个好方法吗:

List结果;映射<整数,字符串>resultsMap = new HashMap();for (Object[] o : 结果) {resultsMap.put((Integer) o[0], (String) o[1]);}

解决方案

List列表;映射<键,项目>map = new HashMap();for (Item i : list) map.put(i.getKey(),i);

当然假设每个 Item 都有一个 getKey() 方法,该方法返回一个正确类型的键.

Recently I have conversation with a colleague about what would be the optimal way to convert List to Map in Java and if there any specific benefits of doing so.

I want to know optimal conversion approach and would really appreciate if any one can guide me.

Is this good approach:

List<Object[]> results;
Map<Integer, String> resultsMap = new HashMap<Integer, String>();
for (Object[] o : results) {
    resultsMap.put((Integer) o[0], (String) o[1]);
}

解决方案

List<Item> list;
Map<Key,Item> map = new HashMap<Key,Item>();
for (Item i : list) map.put(i.getKey(),i);

Assuming of course that each Item has a getKey() method that returns a key of the proper type.

这篇关于如何将列表转换为地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆