Iterator<LookupElement> () { Set<LookupElement> processed = new ReferenceOpenHashSet<>(mySrcSet.size()); Set<Collection<LookupElement>> arraysProcessed = new ReferenceOpenHashSet<>(); final Iterable<? extends LookupElement> next = myNext == null ? mySource : myNext.classify(mySource, myContext); Iterator<LookupElement> base = FilteringIterator.create(next.iterator(), processed::add); return new FlatteningIterator<>(base) { @Override protected @NotNull Iterator<LookupElement> createValueIterator(LookupElement element) { List<LookupElement> toLift; synchronized (LiftShorterItemsClassifier.this) { toLift = new ArrayList<>(myToLift.get(element)); } List<LookupElement> shorter = addShorterElements(toLift); List<LookupElement> singleton = Collections.singletonList(element); if (shorter != null) { if (myLifted != null) { myLifted.addAll(shorter); } Iterable<LookupElement> lifted = myNext == null ? shorter : myNext.classify(shorter, myContext); return (myLiftBefore ? ContainerUtil.concat(lifted, singleton) : ContainerUtil.concat(singleton, lifted)).iterator(); } return singleton.iterator(); } private @Nullable List<LookupElement> addShorterElements(@Nullable Collection<LookupElement> from) { List<LookupElement> toLift = null; if (from == null) { return null; } if (arraysProcessed.add(from)) { for (LookupElement shorterElement : from) { if (mySrcSet.contains(shorterElement) && processed.add(shorterElement)) { if (toLift == null) { toLift = new ArrayList<>(); } toLift.add(shorterElement); } } } return toLift; } }; }