Showing posts with label Hashmap. Show all posts
Showing posts with label Hashmap. Show all posts

Thursday 4 June 2015

HashMap with multiple values under the same key


  1. Use a map that has a list as the value. Map<KeyType, List<ValueType>>.
  2. Create a new wrapper class and place instances of this wrapper in the map. Map<KeyType, WrapperType>.
  3. Use a tuple like class (saves creating lots of wrappers). Map<KeyType, Tuple<Value1Type, Value2Type>>.
  4. Use mulitple maps side-by-side.

Examples

1. Map with list as the value
// create our map
Map<string, List<Person>> peopleByForename = new HashMap<string, List<Person>>();    

// populate it
List<Person> people = new ArrayList<Person>();
people.Add(new Person("Bob Smith"));
people.Add(new Person("Bob Jones"));
peopleByForename.Add("Bob", people);

// read from it
List<Person> bobs = peopleByForename["Bob"];
Person bob1 = bobs[0];
Person bob2 = bobs[1];
2. Using wrapper class
// define our wrapper
class Wrapper {
    public Wrapper(Person person1, Person person2) {
       this.person1 = person1;
       this.person2 = person2;
    }

    public Person getPerson1 { return this.person1; }
    public Person getPerson2 { return this.person2; }

    private Person person1;
    private Person person2;
}

// create our map
Map<string, Wrapper> peopleByForename = new HashMap<string, Wrapper>();

// populate it
Wrapper people = new Wrapper()
peopleByForename.Add("Bob", new Wrapper(new Person("Bob Smith"),
                                        new Person("Bob Jones"));

// read from it
Wrapper bobs = peopleByForename["Bob"];
Person bob1 = bobs.Person1;
Person bob2 = bobs.Person2;
3. Using a tuple
// you'll have to write or download a Tuple class in Java, (.NET ships with one)

// create our map
Map<string, Tuple2<Person, Person> peopleByForename = new HashMap<string, Tuple2<Person, Person>>();

// populate it
peopleByForename.Add("Bob", new Tuple2(new Person("Bob Smith",
                                       new Person("Bob Jones"));

// read from it
Tuple<Person, Person> bobs = peopleByForename["Bob"];
Person bob1 = bobs.Item1;
Person bob2 = bobs.Item2;
4. Multiple maps
// create our maps
Map<string, Person> firstPersonByForename = new HashMap<string, Person>();
Map<string, Person> secondPersonByForename = new HashMap<string, Person>();

// populate them
firstPersonByForename.Add("Bob", new Person("Bob Smith"));
secondPersonByForename.Add("Bob", new Person("Bob Jones"));

// read from them
Person bob1 = firstPersonByForename["Bob"];
Person bob2 = secondPersonByForename["Bob"];