如果你只需要調用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