6

I'm creating a program that needs to store key-value pairs. The program needs to accept requests in the form of keys, and return the respective values.

The problem is that there are sometimes multiple values for each key, and the map class doesn't allow for duplicate keys.

The values are numbers, so I can't meaningfully concatenate the values like I would with strings.

Is there any elegant way of accounting for the fact that there can be more than one numerical value for each key? I want each number to be returned, not just one at random.

oadams
  • 3,019
  • 6
  • 30
  • 53

3 Answers3

20
$ cat YourMap.java
public class YourMap extends HashMap<String, List<Integer>> {
    public void put(String key, Integer number) {
        List<Integer> current = get(key);
        if (current == null) {
            current = new ArrayList<Integer>();
            super.put(key, current);
        }
        current.add(number);
    }

    public static void main(String args[]) {
        YourMap m = new YourMap();
        m.put("a", 1);
        m.put("a", 2);
        m.put("b", 3);
        for(Map.Entry e : m.entrySet()) {
            System.out.println(e.getKey() + " -> " + e.getValue());
        }
    }
}

$ java map
b -> [3]
a -> [1, 2]
Will Hartung
  • 115,893
  • 19
  • 128
  • 203
11

The structure you're looking for is called a "multimap". You can either use an ordinary map with ArrayLists as values, or you can use a multimap implementation. There's a nice one in Google's "guava" toolkit. See here.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
4

If you make the value a list then it will be able to store multiple values for a key

Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
krock
  • 28,904
  • 13
  • 79
  • 85