Home >Java >javaTutorial >How to Randomize Multiple ArrayLists While Maintaining Ordering Consistency?
Maintaining Ordering Across Multiple ArrayLists during Randomization
Randomizing a single ArrayList is a straightforward task, but the challenge arises when multiple ArrayLists, related to each other, need to be randomized in a consistent fashion. To achieve this, we can leverage the power of Collections.shuffle() and a shared random seed.
The following code snippet demonstrates how to achieve the desired result:
<code class="java">import java.util.ArrayList; import java.util.Collections; public class ArrayListRandomization { public static void main(String[] args) { // Initialize the ArrayLists String[] file = {"H1.txt", "H2.txt", "H3.txt", "M4.txt", "M5.txt", "M6.txt"}; ArrayList<String> fileList = new ArrayList<>(Arrays.asList(file)); String[] img = {"e1.jpg", "e2.jpg", "e3.jpg", "e4.jpg", "e5.jpg", "e6.jpg"}; ArrayList<String> imgList = new ArrayList<>(Arrays.asList(img)); // Generate a shared random seed long seed = System.nanoTime(); // Randomize the file list Collections.shuffle(fileList, new Random(seed)); // Randomize the image list using the same seed Collections.shuffle(imgList, new Random(seed)); // Print the randomized ArrayLists System.out.println("Randomized fileList:"); for (String s : fileList) { System.out.println(s); } System.out.println("Randomized imgList:"); for (String s : imgList) { System.out.println(s); } } }</code>
In this code:
By using a shared random seed, both ArrayLists are randomized in the same way, ensuring that the relationship between the corresponding elements is maintained.
The above is the detailed content of How to Randomize Multiple ArrayLists While Maintaining Ordering Consistency?. For more information, please follow other related articles on the PHP Chinese website!