List<Match> (List<Match> matches) { Map<PsiExpression, Set<Match>> patternUsages = new HashMap<>(); for (Match match : matches) { for (ExtractedParameter parameter : match.getExtractedParameters()) { for (PsiExpression patternUsage : parameter.myPatternUsages) { patternUsages.computeIfAbsent(patternUsage, k -> new HashSet<>()).add(match); } } } Set<Match> badMatches = new HashSet<>(); for (Map.Entry<PsiExpression, Set<Match>> entry : patternUsages.entrySet()) { PsiExpression patternUsage = entry.getKey(); Set<Match> patternMatches = entry.getValue(); for (PsiExpression maybeNestedUsage : patternUsages.keySet()) { if (patternUsage == maybeNestedUsage) { continue; } if (PsiTreeUtil.isAncestor(patternUsage, maybeNestedUsage, true)) { badMatches.addAll(patternMatches); break; } } } if (!badMatches.isEmpty()) { matches = new ArrayList<>(matches); matches.removeAll(badMatches); } return matches; }