Java TreeMap 中的重复键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21749386/
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
Duplicate key in TreeMap
提问by zdhim
I have the below code for tree map where I store duplicate key and it seems overwrite the existing one.
我有以下用于存储重复键的树图代码,它似乎覆盖了现有的键。
TreeMap<String, Integer> tm=new TreeMap<>();
tm.put("vivek", 1);
tm.put("vivek", 2);
System.out.println(tm);
It prints {vivek=2}
So it means map allow to overwrite on key basis?
它打印{vivek=2}
所以这意味着地图允许在关键基础上覆盖?
采纳答案by Abimaran Kugathasan
TreeMap#public V put(K key, V value)
API says
TreeMap#public V put(K key, V value)
API 说
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
将指定值与此映射中的指定键相关联。 如果映射先前包含键的映射,则旧值将被替换。
回答by Tim B
All maps share the same basic properties, one of which is that all keys must be unique. Hence why keySet()
returns a Set
.
所有映射共享相同的基本属性,其中之一是所有键都必须是唯一的。因此为什么keySet()
返回 a Set
。
To do what you are looking for you need a Multimap - which is essentially a Map to a List.
要执行您正在寻找的操作,您需要一个 Multimap - 它本质上是一个 Map to a List。
Map<Integer, List<String>> multiMap;
To add an object get the list for that key, if it is null add a list then add your value to the list, otherwise just add your value to the existing list.
要添加一个对象,获取该键的列表,如果它为空,则添加一个列表,然后将您的值添加到列表中,否则只需将您的值添加到现有列表中。
There are some multimap implementation available in various 3rd party libraries or it's easy enough to implement your own.
各种 3rd 方库中都有一些 multimap 实现,或者很容易实现你自己的。