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"};
You can create an array containing the numbers 0 to 5 and shuffle those. Then use the result as a mapping of "oldIndex -> newIndex" and apply this mapping to both your original arrays.
Use
Collections.shuffle()
twice, with twoRandom
objects initialized with the same 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.The simplest approach is to encapsulate the two values together into a type which has both the image and the file. Then build an
ArrayList
of that and shuffle it.That improves encapsulation as well, giving you the property that you'll always have the same number of files as images automatically.
An alternative if you really don't like that idea would be to write the shuffle code yourself (there are plenty of examples of a modified Fisher-Yates shuffle in Java, including several on Stack Overflow I suspect) and just operate on both lists at the same time. But I'd strongly recommend going with the "improve encapsulation" approach.
You could do this with maps:
This will iterate through the images in the random order.
Instead of having two arrays of Strings, have one array of a custom class which contains your two strings.
Not totally sure what you mean by "automatically" - you can create a container object that holds both objects:
public class FileImageHolder { String fileName; String imageName; //TODO: insert stuff here }
And then put that in an array list and randomize that array list.
Otherwise, you would need to keep track of where each element moved in one list, and move it in the other one as well.