CollectTerminal (@NotNull CollectTerminal terminal, @Nullable PsiElement nextElement) { if (nextElement == null) return terminal; List<BiFunction<@NotNull CollectTerminal, @NotNull PsiElement, @Nullable CollectTerminal>> wrappers = Arrays.asList(SortingTerminal::tryWrap, ToArrayTerminal::tryWrap, NewListTerminal::tryWrap, UnmodifiableTerminal::tryWrap); while (true) { CollectTerminal wrapped = null; for (BiFunction<@NotNull CollectTerminal, @NotNull PsiElement, @Nullable CollectTerminal> wrapper : wrappers) { wrapped = wrapper.apply(terminal, nextElement); if (wrapped != null) { terminal = wrapped; break; } } if (wrapped == null) { return terminal; } nextElement = PsiTreeUtil.skipWhitespacesAndCommentsForward(nextElement); if (nextElement == null) { return terminal; } } }