使用java存储键值对

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19872760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:56:28  来源:igfitidea点击:

Storing Key, Value Pair using java

javadata-structuresmap

提问by Awinash

I would like to know the best data structure used in java suitable for the following senario.

我想知道适用于以下 senario 的 java 中使用的最佳数据结构。

  1. There is a key and a value.
  2. And the key is not duplicated,
  3. Each Value should store collection of objects where the values in each object will change frequently.
  1. 有一个键和一个值。
  2. 并且密钥不重复,
  3. 每个值应存储对象的集合,其中每个对象中的值将频繁更改。

Thanks.

谢谢。

采纳答案by Juned Ahsan

HashMapshould serve your need.

HashMap应该可以满足您的需求。

HashMap allows you to store key value pairs as a collection. HashMap does not allow duplicate keys. You can use different collection to be stored as a value in your HashMap. For example to create a map with keys as a String and value as a list, the define it like this:

HashMap 允许您将键值对存储为集合。HashMap 不允许重复键。您可以使用不同的集合作为值存储在 HashMap 中。例如,要创建一个键作为字符串和值作为列表的映射,像这样定义它:

Map<String, List<String>> = new HashMap<String, List<String>>();

Also there are implementations for such collection called MultiMap i.e map where a key is associated with collection of values. Two popular implemantations of MultiMap are:

也有这种集合的实现称为 MultiMap,即映射,其中一个键与值的集合相关联。MultiMap 的两种流行实现是:

  • Apacha MultiMap
  • Guava MultiMap
  • 阿帕查多图
  • 番石榴多图

回答by Lan

A type of map. You aren't saying much besides "I need a key-value thingy". If you need to iterate the map by insertion order, there is a LinkedHashMap. If you need to iterate the map by ascending or descending key values, there are sorted maps. If the map will be shared by multiple threads a concurrent mapwill be useful. If there will be billions of items in the list and you don't mind hemorraghing data (say this is a caching algorithm), a WeakHashMapis for you.

一种地图。除了“我需要一个键值的东西”之外,你并没有说太多。如果您需要按插入顺序迭代映射,则有一个 LinkedHashMap。如果您需要通过升序或降序键值来迭代地图,则可以使用已排序的地图。如果映射将由多个线程共享,则并发映射将很有用。如果列表中有数十亿个项目并且您不介意大量数据(比如这是一种缓存算法),那么WeakHashMap适合您。

If by "key is not duplicated" you mean it is a violation if a key is inserted if it already exists, you have a few options.

如果“密钥不重复”意味着如果密钥已经存在,则插入它是一种违规行为,您有几个选择。