I am computing statistics grouped by an attribute. For each category of this attribute (given as Strings) I get values which I want to aggregate.
For this, I need a map from category to DescriptiveStatistics (provided by org.apache.commons.math.stat.descriptive). In this map, I’d have to check if, for a given category, the corresponding DescriptiveStatistics have been created yet. This check, and the creation of the new DescriptiveStatistics, should be done by the map.
I tested Apache’s LazyMap, but the non-genericity led me to Guava’s LoadingCache. Something along these lines works for me:
LoadingCache<String, DescriptiveStatistics> groupedStats =
CacheBuilder.newBuilder()
.build(new CacheLoader<String, DescriptiveStatistics>() {
@Override
public DescriptiveStatistics load(String key) {
return new DescriptiveStatistics();
}
});
Is there a less “wordy” solution? One that wouldn’t require me to throw in an anonymous class just for instantiating objects?
Your original code is exactly the code the Guava team would like you to write.
We tend to avoid reflection (except, naturally, in
com.google.common.reflect). It tends to be fragile and lose the benefits of compile-time checking — if a particular class doesn’t have a public no-arg constructor, and you usedclazz.newInstance(), you wouldn’t find that out until runtime. Writing the direct implementation might cost you a line or two, but we consider the benefits worth it.