【发布时间】:2012-08-26 23:20:07
【问题描述】:
如何在HashMap的ArrayList中添加元素?
HashMap<String, ArrayList<Item>> Items = new HashMap<String, ArrayList<Item>>();
【问题讨论】:
标签: java data-structures
如何在HashMap的ArrayList中添加元素?
HashMap<String, ArrayList<Item>> Items = new HashMap<String, ArrayList<Item>>();
【问题讨论】:
标签: java data-structures
我知道,这是一个老问题。但只是为了完整起见,lambda 版本。
Map<String, List<Item>> items = new HashMap<>();
items.computeIfAbsent(key, k -> new ArrayList<>()).add(item);
【讨论】:
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);
}
}
【讨论】:
首先你必须添加一个 ArrayList 到 Map
ArrayList<Item> al = new ArrayList<Item>();
Items.add("theKey", al);
然后您可以像这样向 Map 内的 ArrayLIst 添加一个项目:
Items.get("theKey").add(item); // item is an object of type Item
【讨论】:
典型的代码是创建一个显式的方法来添加到列表中,并在添加时动态创建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);
}
【讨论】:
synchronized 标志在这里真的有用吗? ArrayList 和大多数标准集合都不是线程安全的,所以确保这个块是同步的并不是那么有用,对吧?
item = new ... line 上使用除ArrayList 之外的其他内容,例如CopyOnWriteArrayList 等...
#i'm also maintaining insertion order here
Map<Integer,ArrayList> d=new LinkedHashMap<>();
for( int i=0; i<2; i++)
{
int id=s.nextInt();
ArrayList al=new ArrayList<>();
al.add(s.next()); //name
al.add(s.next()); //category
al.add(s.nextInt()); //fee
d.put(id, al);
}
【讨论】: