Re: A filtered iteration over a collection: current idiom?
Le 18/09/2010 16:36, Simon Brooke a ??crit :
I'm looking for the most idiomatic and elegant means of iterating over a
filtered subset of a collection. Here's the basic structure of piece of
code I'm looking at, which must be fairly common:
Vector<Widget> widgets = doSomethingToGetWidgets();
for (Widget widget : widgets) {
if (widget instanceof ActionWidget) {
doSomethingWithActionWidget( (ActionWidget) widget);
}
}
(obviously, ActionWidget is a subclass of Widget)
What I'd like to do would be something like
Vector<Widget> widgets = doSomethingToGetWidgets();
for (ActionWidget widget : widgets
where (widget instanceof ActionWidget)) {
doSomethingWithActionWidget( (ActionWidget) widget);
}
I can't find anything in the Java 5 collections documentation which
offers type filtering functionality; am I missing something?
I personally find the code very easy to read and understand as is, but
you might be interested in apache commons collections :
http://commons.apache.org/collections/
The code could be rewritten as is :
List<Widget> widgets = doSomethingToGetWidgets();
CollectionUtils.forAllDo(widgets, ClosureUtils.ifClosure(
PredicateUtils.instanceOfPredicate(ActionWidget.class),
new Closure() {
@Override
public void execute(Object o) {
doSomethingWithActionWidget((ActionWidget) o);
}
}));
(not compiled, not tested)
Please stop using Vector. List/ArrayList should be preferred.
JB.