String (@NotNull String preferredName, @NotNull Predicate<? super String> nameExistsPredicate) { if (nameExistsPredicate.test(preferredName)) { int numberPos = preferredName.length() - 1; while (numberPos >= 0 && Character.isDigit(preferredName.charAt(numberPos))) { numberPos--; } String baseName = numberPos >= 0 ? preferredName.substring(0, numberPos + 1) : preferredName; if (!baseName.endsWith(COPY_NAME_SUFFIX)) { baseName = preferredName + " " + COPY_NAME_SUFFIX; } if (!nameExistsPredicate.test(baseName)) return baseName; int i = 1; while (true) { String newName = baseName + i; if (!nameExistsPredicate.test(newName)) return newName; i++; } } return preferredName; }