如果你只需要调用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));
}
你期望什么结果? – bcsb1001
arraylist所有元素变得随机破裂 –
我用适合您的问题的解决方案扩展了我的答案。 – Ward