Iterator<AntDomElement> () { final List<DomElement> children = DomUtil.getDefinedChildren(this, true, false); if (children.isEmpty()) { return Collections.emptyIterator(); } final Iterator<DomElement> it = children.iterator(); return new Iterator<>() { private DomElement myUnprocessedElement; @Override public boolean hasNext() { findNextAntElement(); return myUnprocessedElement != null; } @Override public AntDomElement next() { findNextAntElement(); if (myUnprocessedElement == null) { throw new NoSuchElementException(); } final AntDomElement antElement = (AntDomElement)myUnprocessedElement; myUnprocessedElement = null; return antElement; } private void findNextAntElement() { if (myUnprocessedElement != null) { return; } do { if (!it.hasNext()) { break; } myUnprocessedElement = it.next(); } while (!(myUnprocessedElement instanceof AntDomElement)); } @Override public void remove() { Iterator.super.remove(); } }; }