How to add element into ArrayList in HashMap?
HashMap<String, ArrayList<Item>> Items = new HashMap<String, ArrayList<Item>>();
This question is related to
java
data-structures
First you have to add an ArrayList to the Map
ArrayList<Item> al = new ArrayList<Item>();
Items.add("theKey", al);
then you can add an item to the ArrayLIst that is inside the Map like this:
Items.get("theKey").add(item); // item is an object of type Item
Typical code is to create an explicit method to add to the list, and create the ArrayList on the fly when adding. Note the synchronization so the list only gets created once!
@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);
}
#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);
}
I know, this is an old question. But just for the sake of completeness, the lambda version.
Map<String, List<Item>> items = new HashMap<>();
items.computeIfAbsent(key, k -> new ArrayList<>()).add(item);
Source: Stackoverflow.com