4

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);

        }
4
  • 1
    map.get(key).add(value) check for null Commented Jun 13, 2014 at 19:39
  • the hashmap is empty to begin with though Commented Jun 13, 2014 at 19:39
  • if you get null value then create an array list and add value to it and then use put() Commented Jun 13, 2014 at 19:40
  • the hashmap is empty to begin with though can't see it, where is it though? Commented Jun 13, 2014 at 19:46

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

6 Comments

There is no way key could be null, actually the whole validation on the key seems unnecessary. Also, HashMap does allow null key.
use containsKey() that is better than checking value as null.
@BheshGurung Agreed. Edited.
@ElliottFrisch I you like any comment then it's a good practice to up-vote it. Isn't it?
Thank you very much! I implemented it and it worked!
|
2

This is a good use for a guava Multimap, which manages the existence/creation of the inner List.

http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/Multimap.html

http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/ArrayListMultimap.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.