NextNameGenerator { public static String getNextName(final List<String> names, final String newNamePrefix, final String regex) { var pattern = Pattern.compile(String.format("%s %s", newNamePrefix, regex)); var nextName = names.stream() .filter(name -> pattern.matcher(name).find()) .map(name -> { var matcher = pattern.matcher(name); matcher.find(); return Integer.parseInt(matcher.group(1)); }) .sorted((a, b) -> b - a) .findFirst() .map((increment) -> String.format("%s (%s)", newNamePrefix, increment + 1)) .orElse(String.format("%s (1)", newNamePrefix)); return nextName; }  static String getNextName(final List<String> names, final String newNamePrefix, final String regex); static String getNextName(final List<String> names, final String newNamePrefix);  }
@Test void simple() { var names = Arrays.asList("New group", "New group (1)", "New group (2)"); assertThat(NextNameGenerator.getNextName(names, "New group")).isEqualTo("New group (3)"); }
@Test void badNumbers() { var names = Arrays.asList("New group", "New group (1)", "New group (2)", "New group (x)", "New group (99)"); assertThat(NextNameGenerator.getNextName(names, "New group")).isEqualTo("New group (100)"); }
@Test void nothingNew() { var names = Arrays.asList("Some name", "Some other name (343)", "Another name"); assertThat(NextNameGenerator.getNextName(names, "New group")).isEqualTo("New group (1)"); }
@Test void empty() { var names = new ArrayList<String>(); assertThat(NextNameGenerator.getNextName(names, "New group")).isEqualTo("New group (1)"); }