HashMap更新ArrayList

11

我刚开始学习使用HashMap并阅读了Java教程,但是我遇到了麻烦。

我想更新HashMap内部的List,但是我想获取那个键(key)的List,有没有一种方法可以更新特定键(key)的List而不必创建5个不同的List并更新它们?

 HashMap<String, ArrayList<String>> mMap = new HashMap<String, ArrayList<String>>();
        ArrayList<String> list = new ArrayList<String>();
        mMap.put("A", list);
        mMap.put("B", list);
        mMap.put("C", list);
        mMap.put("D", list);

        Iterator iter = mMap.entrySet().iterator();

        if (mMap.containsKey("A"))
        {   
            Map.Entry mEntry = (Map.Entry) iter.next();
            list.add("test");
            mMap.put("A",list);
            System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
        }
        else if (mMap.containsKey("B"))
        {   
            Map.Entry mEntry = (Map.Entry) iter.next();
            list.add("entry");
            mMap.put("B",list);
            System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
        }
6个回答

23

你可以使用以下代码:

mMap.get("A").add("test");
mMap.get("B").add("entry");

1
啊!你比我先回答了;-) - aishwarya
4
当他将相同的列表放入每个映射条目中时,为什么这篇文章会得到3个赞? :-) - user949300
1
我只是回答了他的基本问题:是否有比我现在做的更新列表更简单的方法? - Tudor

7
  1. 像@Tudor所说的,使用mMap.get("A").add("foo");

  2. 您将完全相同的列表放入每个映射条目中。您的初始行应该是

    mMap.put("A", new ArrayList());
    mMap.put("B", new ArrayList()); 
    ...
    mMap.put("Z", new ArrayList());

另一种方法是即时检查的编写方式。

public synchronized void myAdd(String key, String value) {
   List<String> there = mMap.get(key);
   if (there == null) {
      there = new ArrayList<String>();
      mMap.put(key, there);
   }
   there.add(value);
}

2
您可能是指:
HashMap<String, List<String>> mMap = new HashMap<String, List<String>>();
    mMap.put("A", new ArrayList<String>());
    mMap.put("B", new ArrayList<String>());
    mMap.put("C", new ArrayList<String>());
    mMap.put("D", new ArrayList<String>());

    if (mMap.containsKey("A"))
    {   
        mMap.get("A").add("test");
        System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
    }
    else if (mMap.containsKey("B"))
    {   
        mMap.get("B").add("entry");
        System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
    }
   ...

我想知道你是否真的需要那些containsKey检查!希望对你有所帮助!

2
我觉得在你的情况下,可以使用Google GuavaMultimapListMultimap接口以及ArrayListMultimap实现。 选择正确的集合(链接中只列出了标准集合,但Multimap在这种情况下是正确的)可以使代码更易读:
ListMultimap<String, String> myMultimap = ArrayListMultimap.create();
myMultimap.put("A", "test");
myMultimap.put("B", "entry");

然后,myMultimap.get("A")将返回一个列表(实际上是一个ArrayList实例),其中有一个元素:"test",而myMultimap.get("C")将返回一个空列表。
Map<String,List<String>>方法相比:
  • 您不必初始化“C”键为空列表,
  • 您没有null检查(没有NullPointerException),
  • 您不必进行其他检查,例如myMap.containsKey("A")
  • 您编写的代码更少,
  • 因此,您的代码更少容易出错,
  • 等等。

附言:改为:
HashMap<String, ArrayList<String>> mMap = new HashMap<String, ArrayList<String>>();

使用集合时,应该使用接口而不是类。例如:
Map<String, List<String>> mMap = new HashMap<String, List<String>>();

甚至更好的是,Guava有“静态构造函数”(无需重复代码):
Map<String, List<String>> mMap = Maps.newHashMap()

当不需要关于实施的知识时。

1
如果您使用不同的键将相同的列表作为值添加,例如键A、B、C和D都指向同一个列表,并且通过一个键访问和更新列表,则更改将在所有列表中可见。每个键都指向相同的列表结构。
如果您希望这些列表不同,则需要为不同的键使用不同的列表。
您可以自动化此过程,例如通过创建自己的插入方法来克隆给定的列表。

1
我会这样做。
private final ReentrantLock lock = new ReentrantLock();
    Map<String ,List<String>> mMap=new HashMap<>();
    public  void myAdd(String key, String value) {
        try {
            lock.lock();
        List<String> there =mMap.get(key)==null?new ArrayList<>():mMap.get(key);
        there.add(value);
        mMap.put(key, there);
        }finally {
            lock.unlock();
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接