laura
laura

Reputation: 2135

Store in a map a key with multiple values

I want to store in a map keys with multiple values. For example : i am reading from an ArrayList the keys which are Strings and from another ArrayList the values which are integers:

Keys                     Values
humans                   50
elfs                     20
dwarfs                   30
humans                   40
elfs                     10

and i want to store these informations like this: Map < String, ArrayList < Integer>>

[humans = {50,40}]
[elfs = {20,10}]
[dwarfs = {30}]

It is there possible to do this?

Upvotes: 0

Views: 123

Answers (2)

Lucas
Lucas

Reputation: 14909

I do this:

public class StringToListInt {
    private Map<String, List<Integer>> stringToListInt;

    public StringToListInt() {
        stringToListInt = new HashMap<String, List<Integer>>();
    }

    public void addInt( String string, Integer someValue ) {
        List<Integer> listInt = stringToListInt.get( string );
        if ( listInt == null ) {
            listInt = new ArrayList<String>();
            stringToListInt.put( string, listInt );
        }
        listInt.add( someValue );
    }

    public List<Integer> getInts( String string ) {
        return stringToListInt.get( string );
    }
}

If you add in some Generics, I imagine you would end up with something very similar to Guava's MultiMap without the dependency.

Upvotes: 2

Zim-Zam O&#39;Pootertoot
Zim-Zam O&#39;Pootertoot

Reputation: 18148

I recommend using the Guava MultiMap. Alternatively, your

Map<String, ArrayList<Integer>>

will also accomplish this. When doing a put, determine if there is already a list associated with the key; if there is then your put will be a get(key).add(value), otherwise it will be a put(new List(value)). Likewise a remove will remove a value from the associated list, or else will completely remove the list if this will result in an empty list.

Also, a Map<String, HashSet<Integer>> will probably result in better performance than a map of lists; obviously don't do this if you want to associate duplicate values with a key.

Upvotes: 3

Related Questions