如何在HashMap中将元素添加到ArrayList中

lun*_*nar 13 java data-structures

如何在HashMap中将元素添加到ArrayList中?

    HashMap<String, ArrayList<Item>> Items = new HashMap<String, ArrayList<Item>>();
Run Code Online (Sandbox Code Playgroud)

Tob*_*sse 29

HashMap<String, ArrayList<Item>> items = new HashMap<String, ArrayList<Item>>();

public synchronized void addToList(String mapKey, Item myItem) {
    List<Item> itemsList = items.get(mapKey);

    // if list does not exist create it
    if(itemsList == null) {
         itemsList = new ArrayList<Item>();
         itemsList.add(myItem);
         items.put(mapKey, itemsList);
    } else {
        // add if item is not already in list
        if(!itemsList.contains(myItem)) itemsList.add(myItem);
    }
}
Run Code Online (Sandbox Code Playgroud)


pan*_*pan 18

我知道,这是一个老问题.但仅仅为了完整性,lambda版本.

Map<String, List<Item>> items = new HashMap<>();
items.computeIfAbsent(key, k -> new ArrayList<>()).add(item);
Run Code Online (Sandbox Code Playgroud)

  • 有人!!递给这家伙一枚奖章。 (11认同)
  • 这很好用。因为computeIfAbsent()是为了实现一个多值映射,Map&lt;K,Collection&lt;V&gt;&gt;,支持每个key多个值 (4认同)
  • 有史以来最好的解决方案。 (3认同)
  • 干得好,这相当干净,应该被接受。 (2认同)

Tul*_*ova 8

首先,您必须向Map添加ArrayList

ArrayList<Item> al = new ArrayList<Item>();

Items.add("theKey", al); 
Run Code Online (Sandbox Code Playgroud)

那么你可以将一个项添加到Map里面的ArrayLIst,如下所示:

Items.get("theKey").add(item);  // item is an object of type Item
Run Code Online (Sandbox Code Playgroud)


use*_*300 5

典型的代码是创建一个显式方法来添加到列表中,并在添加时动态创建ArrayList.请注意同步,因此列表只会创建一次!

@Override
public synchronized boolean addToList(String key, Item item) {
   Collection<Item> list = theMap.get(key);
   if (list == null)  {
      list = new ArrayList<Item>();  // or, if you prefer, some other List, a Set, etc...
      theMap.put(key, list );
   }

   return list.add(item);
}
Run Code Online (Sandbox Code Playgroud)