Java 中用于重复键、值对的适当集合类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22141178/
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
Appropriate collection class in Java for duplicate key, value pairs
提问by user1168608
Which collection class should i use for the following data
我应该为以下数据使用哪个集合类
(key1, value1)
(key1, value2)
(key2, value3)
(key3, value3)
keys and values are not distinct
键和值没有区别
回答by reto
You can either roll your own implementation of a:
您可以推出自己的实现:
Map<Key, List<Value>>
or use the Multimap from Guava, in their documentation they explain it as:
或使用来自 Guava的Multimap,在他们的文档中,他们将其解释为:
There are two ways to think of a Multimap conceptually: as a collection of mappings from single keys to single values:
a -> 1 a -> 2 a -> 4 b -> 3 c -> 5
or as a mapping from unique keys to collections of values:
a -> [1, 2, 4] b -> 3 c -> 5
有两种方法可以从概念上考虑 Multimap:作为从单个键到单个值的映射集合:
a -> 1 a -> 2 a -> 4 b -> 3 c -> 5
或者作为从唯一键到值集合的映射:
a -> [1, 2, 4] b -> 3 c -> 5
The following blog postexplains some of the advantages of using the Guava collection.
以下博客文章解释了使用 Guava 集合的一些优势。
There is also the MultiValueMap from the Apache Commons Collectionsthat solves the same problem should you have a preference when it comes to external libraries.
如果您对外部库有偏好,Apache Commons Collections中的MultiValueMap也可以解决同样的问题。
回答by wumpz
Another possibility for this use case is the MultiValueMap
of Apache Commons Collections.
此用例的另一种可能性是MultiValueMap
Apache Commons Collections。
回答by Srinivas
Map<List<String>,List<String>> map = new HashMap<List<String>,List<String>>();
List keys = new ArrayList();
keys.add("one");keys.add("one");keys.add("two");keys.add("three");
List values = new ArrayList();
values.add("First");values.add("First12");values.add("second");values.add("second");
map.put(keys, values);
System.out.println(map.keySet().toString());
System.out.println(map.values().toString());
System.out.println("map:"+map.toString());