Elements from an ArrayList
can be shuffled using the Collection.shuffle method.
Collections.shuffle( list );
Here is an example creating a List
with 4 elements a, b, c and d. The content of the List
is written in the output, then the List is shuffled, and the content is written one more time in the output.
import java.util.Arrays; import java.util.Collections; import java.util.List; public class CollectionsShuffleList { public static void main(String[] argv) { List<String> list = Arrays.asList("a", "b", "c", "d"); System.out.println( "Before shuffling: " + list ); // Shuffle the list Collections.shuffle( list ); System.out.println( "After shuffling: " +list ); } }
Before shuffling: [a, b, c, d] After shuffling: [a, c, b, d]