Java:如何转换列表到地图 [英] Java: How to convert List to Map

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

问题描述

最近我和一位同事交谈了什么是将$ code> List 转换成 Map 在Java中的最佳方法如果这样做有任何具体的好处。



我想知道最佳的转换方式,真的很感激任何人可以指导我。



这是一个好办法:

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

谢谢。

解决方案

 列表<项目>名单
Map< Key,Item> map = new HashMap< Key,Item>(); (项目i:列表)
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]);
  }

Thanks.

解决方案

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.

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

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