Nelson.b.austin
Nelson.b.austin

Reputation: 3190

HashMap with ArrayList

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

Answers (2)

Elliott Frisch
Elliott Frisch

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

Related Questions