1

我想在我的map<String,String>. 但我不想用相等的键移动数据。 例子:

map.put("foo","some");
map.put("bar","thing");
map.put("foo","new");

必须返回foo-some,bar-thing,foo-new.

但是没有bar-thing,foo-new

我应该使用哪种地图?

4

2 回答 2

4

您将需要第三方库,因为它不在标准运行时中。Google Guava 库得到积极维护并且非常强大。

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html

于 2013-08-25T22:15:10.407 回答
2

我相信您正在尝试将多个整数映射到单个字符串键。这是可能的,但如果您将密钥映射到List. HashMapa或 a之间的选择TreeMap取决于您是否要保持条目按键排序。

我相信排序不是你要找的;所以,一个HashMap就足够了。

public Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();

然后您可以将多个值添加到同一个键

public void addToMappedList(Map<String, List<Integer>> map,
                                 String key, Integer value) {
    List<Integer> existingValues = map.get(key);
    if (existingValues == null) {
        existingValues = new ArrayList<Integer>();
        map.put(key, existingValues);
    }
    existingValues.add(value);
}

addToMappedList(map, "foo", 1);
addToMappedList(map, "foo", 2);

以下是如何从List. 返回的布尔值将指示是否value实际找到并从其中删除List

public boolean removeFromMappedList(Map<String, List<Integer>> map,
                                         String key, Integer value) {
    List<Integer> existingValues = map.get(key);
    if (existingValues != null) {
        return existingValues.remove(value);
    }
    return false;
}

removeFromMappedList(map, "foo", 1); // true
removeFromMappedList(map, "foo", 3); // false

要删除整个密钥及其List关联,只需Map直接使用

map.remove("foo");
于 2013-08-25T22:14:53.750 回答