This example will show how to shuffle an arraylist using the Collections.shuffle method. The snippet below will use a deck of cards to demonstrate how to randomize position order in list.
Straight up Java @Test
public void shuffle_a_list_java () {
List < String > deckOfCards = new ArrayList < String >();
deckOfCards . addAll (
Arrays . asList (
"Ace" , "2" , "3" , "4" ,
"5" , "6" , "7" , "8" ,
"9" , "10" , "Jack" ,
"Queen" , "King" ));
Collections . shuffle ( deckOfCards );
logger . info ( deckOfCards );
assertThat ( deckOfCards , containsInAnyOrder (
"Ace" , "2" , "3" , "4" ,
"5" , "6" , "7" , "8" ,
"9" , "10" , "Jack" ,
"Queen" , "King" ));
}
Output
[2, 8, King, 10, 6, Ace, 4, Queen, 7, Jack, 3, 9, 5]
Shuffle elements in list posted by Justin Musgrove on 17 November 2013
Tagged: java and java-collections
Share on: Facebook Google+
All the code on this page is available on github:
ShuffleAList.java