Reputation: 3190
I have a java question about a HashMap with an ArrayList in it. The key is a string and the value is the ArrayList (HashMap<String, ArrayList<Object>>
)
I am given a list of multiple keys and I need to put the corresponding values into the ArrayList, and I'm not sure how to do it.
Here's an example:
(What I am given)
ABC
ABC
ABC
123
123
The keys are actually file names so the file is the value for the ArrayList. Now I have to separate those filenames so i can add the files to the ArrayList. Does this make sense?
This is the only code I have:
Set<String> tempModels = Utils.getSettingSet("module_names", new HashSet<String>(), getActivity());
for(String s : tempModels) {
Log.d("Loading from shared preferences: ", s);
String key = s.substring(0, 17);
}
Upvotes: 4
Views: 4393
Reputation: 6306
This is a good use for a guava Multimap, which manages the existence/creation of the inner List.
Upvotes: 2
Reputation: 201527
I believe you're looking for something like this,
List<Object> al = map.get(key);
if (al == null) {
al = new ArrayList<Object>();
map.put(key, al);
}
al.add(value);
Please note that the above uses raw Object
Lists. You should (if possible) pick a proper type, and use it.
Edit
Some prefer the (slightly shorter) form,
if (!map.containsKey(key)) {
map.put(key, new ArrayList<Object>());
}
map.get(key).add(value);
Upvotes: 4