在Java中将对象列表转换为散列表 [英] Convert a list of objects to a hashmap in Java

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

问题描述

我有一个java List< Object> ,每个对象都是一个包含一个字符串和一个整数的字符串。我无法控制List,因为它是由API方法返回的。



我想将列表转换为地图。创建一个你喜欢的类型的地图(HashMap,TreeMap,HashTable ,.)。创建一个你喜欢的类型的地图(HashMap,TreeMap,HashTable ,.)。 ..),然后迭代你的列表并逐个添加所有元素。



没有更好的方法了(除非你愿意编写自己的地图(在某些情况下,它会很好)。



您可以在添加元素之前在您的地图类型上设置一些选项(例如设置尺寸),因为你已经知道要添加多少个元素。这可能会提高性能。编辑:我这样说是因为我理解你的问题的方式是你的列表包含一个字符串和一个整数属性的POJO。如果情况不同,那么答案可能会有所不同。


I have a java List<Object> and each object is a String containing a String and an Integer. I have no control over the List since it is returned by an API method.

I'd like to cast the List to a Map. What is the best way to do this?

解决方案

Create a Map of the type you like (HashMap, TreeMap, HashTable,...) and then iterate through your list and add all elements one by one.

There is no better way (except if you are willing to code your own map that is backed by this list which - in some cases - would be really good).

You MAY set some options on your Map type before adding the elements (such as setting the size) because you already know how many elements to add. That may increase performance a little. Depends heavily on your use case.

EDIT: I said this because I understand your question in a way that your lists contains POJOs with a string and an integer attribute. If that's different, then the answer may be different.

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

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