// at construction, we build up a new list and add all those // objects whose toString() method matches the regular expression public RegexIterable(Iterable<T> it, String regex) { Collection<T> filteredItems = new ArrayList<T>(); for (T t : it) { if (String.valueOf(t).matches(regex)) { filteredItems.add(t); } } this.filteredItems = Collections.unmodifiableCollection(filteredItems); }
// Our iterator then simply walks over that list. public Iterator<T> iterator() { return filteredItems.iterator(); }