Skip to content

Instantly share code, notes, and snippets.

@christophschubert
Created March 18, 2021 12:49
Show Gist options
  • Save christophschubert/6dc01e96afeeed182e7cdc4c7e5ded48 to your computer and use it in GitHub Desktop.
Save christophschubert/6dc01e96afeeed182e7cdc4c7e5ded48 to your computer and use it in GitHub Desktop.
Generate all permutations of Java List. Uses Java 11 var.
public class GeneratePermutations {
static <E> List<E> addToCopy(List<E> original, int pos, E e) {
final var r = new ArrayList<>(original);
r.add(pos, e);
return r;
}
public static <E> List<List<E>> generatePermutations(List<E> original) {
if (original.isEmpty()) {
return List.of(new ArrayList<>());
}
final int size = original.size();
return generatePermutations(original.subList(1, size)).stream().flatMap(
s -> IntStream.range(0, size).mapToObj(i -> addToCopy(s, i, original.get(0)))
).collect(Collectors.toList());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment