I want to shuffle two list in the same fashion. Suppose I have two lists questions and answers. I want to shuffle them both in the same manner so that the question answer pair remains the same.
Asked
Active
Viewed 1,204 times
0
-
You have questions and answers in separate lists? OMG. – sgowd Apr 25 '12 at 09:02
-
4Why not have a simple `QA` class that combines both the question and the answer? That way you only need one list. – Oliver Charlesworth Apr 25 '12 at 09:03
-
Yeah that's a great idea I can use a class. – dnivra Apr 25 '12 at 09:16
2 Answers
6
Java Collections has a (surprisingly) simple solution to this problem: Collections.shuffle(Collection<?>, Random)
with a Random
seeded with same seed.
List<Integer> quests = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> answers = Arrays.asList(10, 20, 30, 40, 50);
long seed = System.nanoTime();
Collections.shuffle(quests, new Random(seed));
Collections.shuffle(answers, new Random(seed));
System.out.println(quests);
System.out.println(answers);
Note:
Extra optimization is dangerous. This DOE NOT WORK:
long seed = System.nanoTime();
Random rnd = new Random(seed);
Collections.shuffle(quests, rnd);
Collections.shuffle(answers, rnd);

Thamme Gowda
- 11,249
- 5
- 50
- 57
3
Instead of two separate lists, you should rather keep your question-answer pairs in either a Map<YourQuestionType, YourAnswerType>
, or a List<YourQuestionAnswerPair>
.
For a generic solution to the latter, this thread may also be useful.

Community
- 1
- 1

Péter Török
- 114,404
- 31
- 268
- 329
-
The problem the application runs on a server and every student should get the questions in random order. And the difficulty in using a map is that I cannot shuffle it. – dnivra Apr 25 '12 at 09:09
-
@dnivra, you can't shuffle the Map directly, but you may extract a list of all its keys to a separate List and shuffle that. If you want to have a different ordering for each user, you need to shallow copy your source collection anyway, be it a List or a Map. So using a Map is actually more effective as you only copy the collection of keys (questions), but not the values (answers). – Péter Török Apr 25 '12 at 09:13