Iterator<FoldRegion> (@NotNull Editor editor) { final FoldRegion[] allRegions = editor.getFoldingModel().getAllFoldRegions(); return new Iterator<>() { private int sectionStart; private int current; private int sectionEnd; { advanceSection(); } private void advanceSection() { sectionStart = sectionEnd; //noinspection StatementWithEmptyBody for (sectionEnd = sectionStart + 1; sectionEnd < allRegions.length && allRegions[sectionEnd].getStartOffset() == allRegions[sectionStart].getStartOffset(); sectionEnd++) { } current = sectionEnd; } @Override public boolean hasNext() { return current > sectionStart || sectionEnd < allRegions.length; } @Override public FoldRegion next() { if (!hasNext()) { throw new NoSuchElementException(); } if (current <= sectionStart) { advanceSection(); } return allRegions[--current]; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }