如果您只是在多维列表上调用Collection.shuffle,它将打乱该列表中子列表的顺序。
如果您想改组所有子列表,则必须为每个子列表调用 Collection.shuffle。
final List<List<String>> list = Arrays.asList(
Arrays.asList("A", "B", "C"),
Arrays.asList("X", "Y", "Z"),
Arrays.asList("1", "2", "3")
);
// 1. Will shuffle the order of the sub-lists
Collections.shuffle(list);
// 2.a. Will shuffle all the sub-lists
list.forEach(sublist -> Collections.shuffle(sublist));
// 2.b. Or the same, with method reference instead of lambda
list.forEach(Collections::shuffle);
编辑问题后编辑
如果真的需要打乱所有子列表的所有元素,甚至在子列表之间混合元素,上面的代码是不够的。
以下代码将按照您的要求执行,但它会假定所有子列表的大小相同(在本例中为 3):
// 1. Add all values in single dimension list
List<String> allValues = list.stream()
.flatMap(List::stream)
.collect(toList());
// 2. Shuffle all those values
Collections.shuffle(allValues);
// 3. Re-create the multidimensional List
List<List<String>> shuffledValues = new ArrayList<>();
for (int i = 0; i < allValues.size(); i = i + 3) {
shuffledValues.add(allValues.subList(i, i+3));
}