Languages that have closures, such as Ruby, enable elegant constructs to transform lists. Suppose we have a class
class QueryTerm {
String value;
public String getValue() {...}
}
and a list of terms List<QueryTerm> terms, that we want to transform into its list of values List<String> values.
In Ruby we could write something like:
values1 = terms.collect do |term|
term.getValue()
end
Java forces us to construct the result list and iterate through the terms collection ourselves (at least there is no iterator or index position involved since foreach was introduced):
Collection<String> values2 = new HashSet<String>();
for (QueryTerm term : terms) {
values2.add(term.getValue());
}
Apache Commons and Google Collections2 try to emulate closures in Java by using anonymous classes:
Collection<String> values3 = Collections2.transform(terms, new Function<QueryTerm, String>() {
@Override
public String apply(QueryTerm term) {
return term.getValue();
}
});
The weird thing is, that this version has more lines of code and more characters than the original version! I would assume it is harder to understand for this reason. Therefore I dismissed the idea back when I saw it in Apache Commons. However, having seen it introduced in Google Collections recently I am starting to wonder if I am missing something.
Therefore my question: What is your opinion of the constructs above? Do you consider the Collections2.transform() version more readable/understandable than the default one? Am I missing something completely?
Best regards, Johannes