I have two arraylist filelist
and imgList
which related to each other, e.g. "H1.txt" related to "e1.jpg". How to automatically randomized the list of imgList
according to the randomization of fileList
? Like in excel, if we sort certain column, the other column will automatically follow?
String [] file = {"H1.txt","H2.txt","H3.txt","M4.txt","M5.txt","M6.txt"};
ArrayList<String> fileList = new ArrayList<String>(Arrays.asList(file));
String [] img = {"e1.jpg","e2.jpg","e3.jpg","e4.jpg","e5.jpg","e6.jpg"};
ArrayList<String> imgList = new ArrayList<String>(Arrays.asList(img));
//randomized files
Collections.shuffle(fileList);
output after randomization e.g.:
fileList = {"M4.txt","M6.txt","H3.txt","M5.txt","H2.txt","H1.txt"};
intended output:
imgList = {"e4.jpg","e6.jpg","e3.jpg","e5.jpg","e2.jpg","e1.jpg"};
Use Collections.shuffle()
twice, with two Random
objects initialized with the same seed:
long seed = System.nanoTime();
Collections.shuffle(fileList, new Random(seed));
Collections.shuffle(imgList, new Random(seed));
Using two Random
objects with the same seed ensures that both lists will be shuffled in exactly the same way. This allows for two separate collections.