A common type of datastructure I might use is a
Map<String,List<MyObject>> myMap...
The common operation I'd do is to add an object to the list given a matching key. For example,
myMap.addValueToList("Key", myObject)
Implementing this is not very tricky, but it is a bit ugly (for this example, assume that myObject contains the key):
for (MyObject myObject : myObjects) {
List<MyObject> newList = newArrayList();
if (myMap.contains(myObject.key)) {
newList = myMap.get(myObject.key);
}
newList.add(myObject);
myMap.put(myObject.key, newList);
}
I do this kind of operation more often than I'd like. Last time, I wrote my own class for this functionality, but I wonder if there isn't some kind of implementation available in one of the commonly used libraries such as apache.
new ArrayList()only when the key is not in the map, and you only need theputoperation in this case, too.