如何生成List <List <String >>的所有排列?

时间:2019-10-10 01:24:42

标签: java java-stream

我正在尝试生成List<List<String>>的所有排列,但没有得到唯一的排列。

我的List<List<String>>看起来像

[
 [Test, Test 1, Test 2],
 [Apple, Sandwich, Banana],
 [Cake, Ice Cream, Fruit]
] 

我正在尝试获取父List<String中每个List<String>的所有组合。因此,例如,第一个实例应具有:

[Test, Test 1, Test 2]
[Test, Test 2, Test 1]
[Test 2, Test, Test 1]
[Test 2, Test 1, Test]
[Test 1, Test, Test 2]
[Test 1, Test 2, Test]

现在,我的尝试将只是迭代并重复元素而不更改顺序,因此将[Test, Test 1, Test 2]重复父List<String>的大小。这是我的方法。任何帮助表示赞赏:

List<List<String>> allPerms = parentList.stream().map(line -> parentList.stream()).flatMap(l -> l.filter(j -> !j.equals(l))).collect(Collectors.toList());

1 个答案:

答案 0 :(得分:4)

使用CollectionUtils.permutations

public static void showAllPermuteByCommons(List<String> list) {
    CollectionUtils.permutations(list) //
            .stream() //
            .forEach(System.out::println);
}

或回溯

public static void permute(List<String> list, int left, int right) {
    if (left == right) {
        System.out.println(Arrays.toString(list.toArray()));
        return;
    }
    for (int j = left; j <= right; j++) {
        Collections.swap(list, left, j);
        permute(list, left + 1, right);
        Collections.swap(list, left, j);
    }
}

public static void showAllPermute(List<String> list) {
    int size = list.size();
    permute(list, 0, size - 1);
}

测试

List<List<String>> list = new ArrayList<>();
list.add(Arrays.asList("Test", "Test 1", "Test 2"));
list.add(Arrays.asList("Apple", "Sandwich", "Banana"));
list.add(Arrays.asList("Cake", "Ice Cream", "Fruit"));

// list.forEach(t -> showAllPermuteByCommons(t));
list.forEach(t -> showAllPermute(t));

输出

[Test, Test 1, Test 2]
[Test, Test 2, Test 1]
[Test 2, Test, Test 1]
[Test 2, Test 1, Test]
[Test 1, Test 2, Test]
[Test 1, Test, Test 2]
[Apple, Sandwich, Banana]
[Apple, Banana, Sandwich]
[Banana, Apple, Sandwich]
[Banana, Sandwich, Apple]
[Sandwich, Banana, Apple]
[Sandwich, Apple, Banana]
[Cake, Ice Cream, Fruit]
[Cake, Fruit, Ice Cream]
[Fruit, Cake, Ice Cream]
[Fruit, Ice Cream, Cake]
[Ice Cream, Fruit, Cake]
[Ice Cream, Cake, Fruit]