Commons Collections By Example: Maps
Thursday, February 9th, 2006I realized today just how much I used the Commons Collections library. Sure, there’s alot of anonymous inner classes, but after years of writing Swing I’ve gotten used to sort of crossing my eyes and looking past the syntactic cruft.
Here’s a silly example. Let’s map the names in the Greek alphabet to actual letters. Here’s our data
Map nameToLetter = new HashMap();
nameToLetter.put("ALPHA","a");
nameToLetter.put("BETA","b");
nameToLetter.put("GAMMA","g");
nameToLetter.put("DELTA","d");
String[] values = {"ALPHA","BETA","GAMMA","GAMMA","DELTA","EPSILON"};
List valueList = Arrays.asList(values);
Let’s convert that valueList to the letters:
Collection resultCollection = CollectionUtils.collect
(
valueList,
TransformerUtils.mapTransformer(nameToLetter)
);
System.out.println(resultCollection);
>[a, b, g, g, d, null]
Hmm…how do we go back the other way….
(more…)