如何在Java中使用键名及其值存储数据?
我有一种情况,我想将数据存储在带有键及其值的对象中。键名相同,但值已更改。我尝试使用哈希映射,但它也不支持这一点。它会覆盖所有值并仅给我成对的最近值。
我的问题是:有没有任何类或方法可以帮助我解决这个问题?
I have a situation where i want to store data in an object with a key and its value. The key name is the same, but the value is changed. i tried to use hash Map but it also does not support this. it overwrites all values and gives me only the recent value in pair.
my question is: are there any classes or methods that can help me sort out this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用什么数据结构
如果要求为单个键存储多个值,则使用 multimap 将是一个不错的选择。
这种多重映射的一种实现是 来自 Google Guava 库的
Multimap
。Guava 中的 Multimap 接口有多种实现,具体取决于键和值的多重性和顺序的要求。
选择实现
一个简单的实现是
HashMultimap
,其中键映射的值不允许重复,并且键的顺序不是决定性的。ArrayListMultimap
保留映射到键的值的顺序,按照它们映射到键的顺序。
What data structure to use
If the requirement is to store multiple values for a single key, then using a multimap would be a good option.
One implementation of such a multimap is the
Multimap
from the Google Guava library.The
Multimap
interface in Guava has several implementations depending on the requirements for the multiplicity and ordering of the keys and values.Choosing an implementation
A simple implementation is the
HashMultimap
, where the values mapped by a key will not allow duplicates, and the ordering of the keys are not determinant.The
ArrayListMultimap
preserves the order of the values mapped to a key, in the order at which they were mapped to the key.如果您需要跟踪多个值,您可以在映射中使用
List
值。如果满足您的要求,您可以假设列表中的最后一个值是最新值。创建这样的映射将像这样完成(尽管您的键和值类型不必是字符串,它们可以是您正在使用的任何类):
然后要获取给定键的最新值,您需要获取相应列表的最后一个元素:
要向映射添加值,如果新键不存在值,则需要添加逻辑来创建新列表,否则将新值添加到列表末尾:
If you need to keep track of multiple values, you could possibly use a
List
value in the Map. You could use the assumption that the last value in the List is the most recent value, if that meets your requirements.Creating such a map would be done like this (though your key and value types don't have to be Strings, they could be whatever classes you're using):
Then to get the latest value for a given key, you'd need to get the last element of the corresponding list:
To add a value to the Map, you'd need to add logic to create a new list if no value exists for a new key, otherwise add the new value to the end of the list:
Java 的标准集合不包含所谓的“多重映射”类,但其他几个集合库提供了此功能。例如:
Java's standard collections don't include a class for so-called "multimaps", but several other collection libraries offer this feature. Eg: