How can I shuffle the elements of a Collection?
Created May 8, 2012
Brandon Rohlfs
The Collections class which can be found within the java.util namespace provides two methods which suffle the elements of a Collection.
static void shuffle(List<?> list) static void shuffle(List<?> list, Random rnd)The first method shuffles the elements according to a default source of randomness, with the second using a specified source of randomness.
import java.util.*; public class ShuffleTest{ public static void main(String[] args){ List<String> sl = new ArrayList<String>(); sl.add("One"); sl.add("Two"); sl.add("Three"); sl.add("Four"); sl.add("Five"); sl.add("Six"); for(String s: sl){ System.out.println(s); } System.out.println(); Collections.shuffle(sl); for(String s: sl){ System.out.println(s); } } }