If I use HashMap<String, ArrayList<String>> in Java

旧城冷巷雨未停 提交于 2019-12-12 04:05:15

问题


I use HashMap<String, ArrayList<String>> in Java.

When input value is comes,

For example, input value is [1, "stack"], [2, "over"], [1, "flow"].....

I want to enter value [1, ["stack", "flow"]], [2, "over"] in HashMap.

But key value is duplicate. So, HashMap was overwrite.

So, What can I do?


回答1:


Try a Guava Multimap:

The traditional way to represent a graph in Java is Map<V, Set<V>>, which is awkward in a number of ways. Guava's Multimap framework makes it easy to handle a mapping from keys to multiple values.

A ListMultimap will map keys to a List of values, keeping track of their order, while a SetMultimap will map keys to a Set of distinct values.




回答2:


Call get on the Map. If it returns a List (Set may be more appropriate) add to that. If it returns null, create a collection, add the value, put it in the map.

Better, use some third-party multimap.



来源:https://stackoverflow.com/questions/11444628/if-i-use-hashmapstring-arrayliststring-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!