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.

Java相关问答推荐

虚拟线程似乎在外部服务调用时阻止运营商线程

gitlab ci不会运行我的脚本,因为它需要数据库连接'

Springdoc Whitelabel Error Page with Spring V3

在Java中测试DAO方法:假实现与内存数据库

Javascript在边界中心调整ImageView大小

Java 8中的多个字段和计数

Spring Boot 3.2.2中的@Inject和@Resource Remove

我不能再在Android Studio Hedgehog上用Java语言创建新项目了吗?

无法使用ApacheSpark依赖项构建JavaFX应用程序

如何在JavaFX中处理多个按钮

在一行中检索字符分隔字符串的第n个值

如何处理两个几乎相同的XSD文件?

在java中使用不同的application.properties-jar而不使用Spring

Oracle中从JSON中提取和插入数据

在Java中将对象&转换为&q;HashMap(&Q)

接受类及其接口的Java类型(矛盾)

Java 17与Java 8双重表示法

Spring Mapstruct如何获取Lazy初始化实体字段的信息?

如何调查进程列表中不可见的活跃 MySQL 事务?

以较小的时间复杂度找到最大值的最小值