Collection<Group> (@NotNull AbstractTreeNode<?> parent, @NotNull Collection<TreeElement> children) { List<Group> result = new ArrayList<>(); Collection<String> parentGroupUsedStrings = parent.getValue() instanceof StringGroup ? ((StringGroup)parent.getValue()).myChildrenUsedStrings : Collections.emptySet(); Collection<TreeElement> elements = new LinkedHashSet<>(children); for (String subString : mySubStrings) { if (parentGroupUsedStrings.contains(subString)) continue; Set<String> childrenStrings = new HashSet<>(parentGroupUsedStrings); ContainerUtil.addAll(childrenStrings, mySubStrings); StringGroup group = new StringGroup(subString, elements, childrenStrings); Collection<TreeElement> groupChildren = group.getChildren(); if (!groupChildren.isEmpty()) { elements.removeAll(groupChildren); result.add(group); } } return result; }