List<MyFoldingDescriptorWrapper> (Collection<? extends FoldingDescriptor> descriptors) { List<FoldingDescriptor> sorted = new ArrayList<>(descriptors.size()); sorted.addAll(descriptors); sorted.sort((descriptor1, descriptor2) -> { int pos1 = descriptor1.getElement().getTextRange().getStartOffset(); int pos2 = descriptor2.getElement().getTextRange().getStartOffset(); return pos1 - pos2; }); Stack<FoldingDescriptor> stack = new Stack<>(); List<MyFoldingDescriptorWrapper> result = new ArrayList<>(); for (FoldingDescriptor descriptor : sorted) { while (!stack.isEmpty() && descriptor.getRange().getStartOffset() >= stack.peek().getRange().getEndOffset()) stack.pop(); result.add(new MyFoldingDescriptorWrapper(descriptor, stack.size())); stack.push(descriptor); } return result; }