来看最后一组 - Iterator。
LoopingIterator
ArrayListIterator
FilterIterator
UniqueFilterIterator
IteratorUtils
java.util.Iterator接口定义了标准的Collection遍历方法,但是如果不做改变的使用它,我们得到的是从头到尾一次性的遍历。假如我们需要循环遍历,假如我们需要遍历某一段,假如我们需要遍历满足某些条件的元素,等等等等,我们就不能完全依赖于这个Iterator的标准实现了。除非我们宁可在此基础上在调用的代码中多加一些判断,不过这样的话代码就会显得混乱,时间长了就容易变得难以维护。Commons Collections的这一组Iterator为我们带来了便利。
这些Iterator使用都很一目了然,直接看例子吧:
package sean.study.commons.collections;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.collections.Predicate;
import org.apache.commons.collections.iterators.ArrayListIterator;
import org.apache.commons.collections.iterators.FilterIterator;
import org.apache.commons.collections.iterators.LoopingIterator;
import org.apache.commons.lang.StringUtils;
public class IteratorUsage {
public static void main(String[] args) {
demoIteratorUsage();
}
public static void demoIteratorUsage() {
System.out.println(StringUtils.center(" demoClosureUsage ", 40, "="));
// data setup
String[] weekDays = {
"Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"
};
List weekDayList = Arrays.asList(weekDays);
// workdays
Iterator iter1 = new ArrayListIterator(weekDays, 0, 5);
printColl("Partial:", iter1, 5);
// loop
Iterator iter2 = new LoopingIterator(weekDayList);
printColl("
Loop:", iter2, 10);
// looping workdays
Predicate notWeekendPredicate = new Predicate() {
public boolean evaluate(Object obj) {
String str = (String) obj;
if ("Saturday".equalsIgnoreCase(str)) {
return false;
}
if ("Sunday".equalsIgnoreCase(str)) {
return false;
}
return true;
}
};
Iterator iter3 = new FilterIterator(
new LoopingIterator(weekDayList),
notWeekendPredicate
);
printColl("No Weekends loop:", iter3, 12);
System.out.println(StringUtils.repeat("=", 40));
}
public static void printColl(String label, Iterator iter, int maxCount) {
if (StringUtils.isNotBlank(label)) {
System.out.println(label);
}
int i = 0;
while (iter.hasNext() && i < maxCount) {
System.out.println("# " + iter.next() + " #");
i++;
}
}
}
运行结果如下:
=========== demoClosureUsage ===========
Partial:
# Monday #
# Tuesday #
# Wednesday #
# Thursday #
# Friday #
Loop:
# Monday #
# Tuesday #
# Wednesday #
# Thursday #
# Friday #
# Saturday #
# Sunday #
# Monday #
# Tuesday #
# Wednesday #
No Weekends loop:
# Monday #
# Tuesday #
# Wednesday #
# Thursday #
# Friday #
# Monday #
# Tuesday #
# Wednesday #
# Thursday #
# Friday #
# Monday #
# Tuesday #
========================================
有了这些实用的Iterator类,我们就可以轻松的实现可配置的遍历行为了。