如何在 Java 中使用具有重复键的 HashMap?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18968479/
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 12:58:09  来源:igfitidea点击:

How can i have a HashMap in Java with duplicate keys?

javahashmap

提问by programmer

I need a collection in Java that is going to store a pair, a key and a value.

我需要一个 Java 集合来存储一对、一个键和一个值。

So I decided to use a HashMap<String,String>, but I noticed that when I try to add a key that already exists, the previous (key,value) is replaced by the new one (NewKey,NewValue) and the previous entry is lost. So when I have duplicate keys, the previous key is replaced by the new one.

所以我决定使用 a HashMap<String,String>,但我注意到当我尝试添加一个已经存在的键时,之前的 (key,value) 被新的 (NewKey,NewValue) 替换,并且之前的条目丢失了。所以当我有重复的键时,以前的键会被新的键替换。

How can I have a HashMap with duplicate keys?

我怎样才能拥有一个带有重复键的 HashMap?

采纳答案by Eugen Halca

you need MultiMap, take a look at Google Guava Multimap

你需要MultiMap,看看Google Guava Multimap

回答by Ted Hopp

If you want to map a key to a collection of values, take a look at Guava's Multimap. If you don't want to use a third-party library, you can simulate a Multimapwith a Map<String, Collection<String>>. The Java tutorial on the Mapinterfacehas an example of implementing a Multimap.

如果要将键映射到值集合,请查看 Guava 的Multimap. 如果不想使用第三方库,可以模拟一个Multimap带有Map<String, Collection<String>>. 该上的Java教程Map接口具有实现的一个例子Multimap