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.
$ 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With