Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java map with duplicate keys [duplicate]

Tags:

java

map

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.

like image 492
oadams Avatar asked Mar 26 '11 04:03

oadams


1 Answers

$ 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]
like image 169
Will Hartung Avatar answered Oct 30 '22 10:10

Will Hartung