I have a list of Things, which each have a category (an int). What I want to end up with is a Map, where the key is the category, and the value is a List of all of the Things of that category. At the moment I’m having to do this fairly manually, so I’m wondering if there’s some sort of type that I’m not aware of.
At present I do something like the following:
List<Thing> things = thingGenerator.generateTheThings();
Map<Integer,List<Thing>> categoriesOfThing = new TreeMap<Integer,List<Thing>>();
for(Thing thing : things) {
int thingCategory = thing.getCategory();
List<Thing> oneCategoryOfThing;
if(categoriesOfThing.containsKey(thingCategory) {
oneCategoryOfThing = categoriessOfThings.get(thingCategory);
}
else {
oneCategoryOfThing = new ArrayList<Thing>();
}
oneCategoryOfThing.add(thing);
categoriesOfThing.put(thingCategory,oneCategoryOfThing);
}
for(int i = 0; i < numberOfCategories; i++) {
List<Thing> similarThings = categoriesOfThing.get(i);
foo(similarThings);
}
What I’d like to be able to do is something a bit like the following:
List<Thing> things = thingGenerator.generateTheThings();
ChainedMap<Integer,Thing> categoriesOfThing = new ChainedMap<Integer,Thing>();
for(Thing thing : things) {
categoriesOfThing.add(thing.getCategory(), thing);
}
for(int i = 0; i < numberOfTypes; i++) {
List<Thing> similarThings = categoriesOfThing.get(i);
foo(similarThings);
}
Much like the Apache MultiKey allows for multiple keys to be used in a map, I’d like multiple values to be retrievable in a List.
It’s been suggested elsewhere in the comments that the OP should use Guava — among other things, it provides generics, unlike the linked Apache documentation — so here’s the Guava solution. (Disclosure: I contribute to Guava.)
Or, if you want to do it explicitly instead of using
Multimaps.index, it’s possibly even simpler: