我想要一个具有重复键的映射。
我知道有很多map实现(Eclipse向我展示了大约50个),所以我打赌肯定有一个允许这样做。我知道编写自己的地图很容易做到这一点,但我更愿意使用一些现有的解决方案。
也许是commons-collections或google-collections中的一些东西?
发布于 2009-06-30 10:44:40
您正在搜索multimap,实际上commons-collections和Guava都有几个实现。多重映射允许通过维护每个键的值集合来支持多个键,例如,您可以将单个对象放入映射中,但您可以检索一个集合。
如果您可以使用Java5,我更喜欢Guava的Multimap,因为它是泛型感知的。
发布于 2011-06-15 10:57:14
我们不需要依赖Google Collections外部库。您可以简单地实现以下Map:
Map<String, ArrayList<String>> hashMap = new HashMap<String, ArrayList>();
public static void main(String... arg) {
// Add data with duplicate keys
addValues("A", "a1");
addValues("A", "a2");
addValues("B", "b");
// View data.
Iterator it = hashMap.keySet().iterator();
ArrayList tempList = null;
while (it.hasNext()) {
String key = it.next().toString();
tempList = hashMap.get(key);
if (tempList != null) {
for (String value: tempList) {
System.out.println("Key : "+key+ " , Value : "+value);
}
}
}
}
private void addValues(String key, String value) {
ArrayList tempList = null;
if (hashMap.containsKey(key)) {
tempList = hashMap.get(key);
if(tempList == null)
tempList = new ArrayList();
tempList.add(value);
} else {
tempList = new ArrayList();
tempList.add(value);
}
hashMap.put(key,tempList);
}请确保对代码进行微调。
发布于 2014-10-09 16:36:06
Multimap<Integer, String> multimap = ArrayListMultimap.create();
multimap.put(1, "A");
multimap.put(1, "B");
multimap.put(1, "C");
multimap.put(1, "A");
multimap.put(2, "A");
multimap.put(2, "B");
multimap.put(2, "C");
multimap.put(3, "A");
System.out.println(multimap.get(1));
System.out.println(multimap.get(2));
System.out.println(multimap.get(3));输出为:
[A,B,C,A]
[A,B,C]
[A]注意:我们需要导入库文件。
http://www.java2s.com/Code/Jar/g/Downloadgooglecollectionsjar.htm
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;或https://commons.apache.org/proper/commons-collections/download_collections.cgi
import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.map.MultiValueMap;https://stackoverflow.com/questions/1062960
复制相似问题