PsiElement (PsiElement element, boolean keepStream) { boolean replaced = true; while(replaced) { replaced = false; Map<PsiMethodCallExpression, CallChainSimplification> callToSimplification = StreamEx.ofTree(element, e -> StreamEx.of(e.getChildren())) .select(PsiMethodCallExpression.class) .mapToEntry(CALL_TO_FIX_MAPPER::mapFirst) .nonNullValues() .chain(s -> keepStream ? s.filterValues(CallChainSimplification::keepsStream) : s) .toCustomMap(LinkedHashMap::new); for (Map.Entry<PsiMethodCallExpression, CallChainSimplification> entry : callToSimplification.entrySet()) { if(entry.getKey().isValid()) { PsiElement replacement = entry.getValue().simplify(entry.getKey()); if(replacement != null) { replaced = true; if(element == entry.getKey()) { element = replacement; } } } } } return element; }