java - HashMap<String, ArrayList>,根据 Key 为 ArrayList 添加新值

标签 java arraylist hashmap

我遇到了一个测试驱动开发问题(我需要根据提供的 junit 方法使其工作)基于实现一个 HashMap,该 HashMap 使用字符串作为键,ArrayLists 作为值。键需要能够支持一个或多个对应的值。我需要以一种可以从散列中添加或减去值的方式设置我的方法,然后查看散列的更新内容。我的努力是获取从下面显示的单元方法(执行 myClass 及其 addingMethod 方法)方法提供的信息,并将其正确放入哈希中。

void add() {
    myClass = new MyClass("key1", "value1");
    myClass.addingMethod("blargh", "blarghvalue");
    myClass.addingMethod("blargh2", "uglystring");
    myClass.addingMethod("blargh", "anotherstring");
    //and so on and so on............

对于我的最终结果,当我打印出 myClass 的结果时,我需要看到如下内容: {blargh=[blarghvalue, anotherstring], blargh2=uglystring}

我需要能够对此进行添加和删除值。

我对 Java 集合还很陌生(很明显)。如果它们只有 1 对 1 的关系,并且 hashmap 是 1:1,我就能让事情正常进行。所以一个非常简单的 addingMethod 是这样的:

public void addingMethod(String key, String value) {
    hashMap.put(key, value);

将得到一个字符串 string hashmap,但是当然如果我用一个新的键值对重用一个键,原始键值就会被踩到并消失。但是,当谈到动态地使用散列映射和数组列表时,并且超出 1:1 键:值关系时,我迷路了。

最佳答案

听起来你需要一个 MultiMap , 由 Google 的大神 Guava libraries 提供:

A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.

关于java - HashMap<String, ArrayList>,根据 Key 为 ArrayList 添加新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13095076/

相关文章:

具有隔离键/值的 C++ 缓存友好 HashMap

java - GJC——一个外部 jar

java - 在映射中使用 <cword> 的 VIM 问题

java - 如何从 ArrayList<String> 中删除括号

java - 我们为什么需要 ArrayList 构造函数中的 super() 呢?

Java:使用另一个 map 的信息创建一个新 map ,而不是创建引用

Java排序和HashMap

java - 使用 Univocity 将注释 bean 转为部分记录

java - 使用假列表类

java - 如何查找 ArrayList 中的字符串是否包含字符形式的数字