Skip to main content

Expanded options for common generic collections

 

Across a number of companies and orgs, I routinely see people using what are essentially multimaps with a Map<Object, List<Object>> construction because the support for generics hasn't made available, so it's just as fast to write the logic every time as making a new class every time.

 

With generics, we'll be able to replace this:

Map<Id, List<SomeObject>> mapOfLists = new Map<Id, List<SomeObject>>();

// Add/put value

Id key = '00000000000AAAA';

SomeObject newValue = getSomeObject();

List<SomeObject> values = mapOfLists.get(key);

if (values == null) {

values = new List<SomeObject>();

values.add(newValue);

mapOfLists.put(key, values);

} else {

values.add(newValue);

}

// Iterate over stored list

List<SomeObject> values = mapOfLists.get(key);

if (values != null) {

for (SomeObject obj : values) {

// Do something

}

}

With this:

Multimap<Id, SomeObject> multimap = new Multimap<Id, SomeObject>();

// Add/put value:

Id key = '00000000000AAAA';

SomeObject newValue = getSomeObject();

multimap.put(key, newValue);

// Iterate over stored list

for (SomeObject obj : multimap.get(key)) {

// Do something

}

Where previously, making the above generic would only work with a specific type of object. Defining Multimap as a "Map<Id, List<SObject>>" is common, but not as dynamic as a generic such as the above that may not use Id as the key, or an SObject as the value.

 

Generics would also allow users to make their own implementations (or wrappers) of existing classes, such as to add a "getOrDefault" or "putIfAbsent" methods to their Map implementation, without needing to reference utility methods.

0/9000