How can I shuffle the elements of a Collection?

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); 
  }
 }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact