Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick multiple random elements from a list in Java [duplicate]

Tags:

So say I have

List<String> teamList = new LinkedList<String>() teamList.add("team1"); teamList.add("team2"); teamList.add("team3"); teamList.add("team4"); teamList.add("team5"); teamList.add("team6"); 

Is there a simple way of picking... say 3 out the 6 elements in this list in a randomized way without picking the same element twice (or more times)?

like image 202
Ren Avatar asked Dec 04 '11 21:12

Ren


2 Answers

Try this:

public static List<String> pickNRandom(List<String> lst, int n) {     List<String> copy = new ArrayList<String>(lst);     Collections.shuffle(copy);     return n > copy.size() ? copy.subList(0, copy.size()) : copy.subList(0, n); } 

I'm assuming that there are no repeated elements in the input list, also I take the precaution of shuffling a copy for leaving the original list undisturbed. Use it like this:

List<String> randomPicks = pickNRandom(teamList, 3); 
like image 117
Óscar López Avatar answered Oct 24 '22 07:10

Óscar López


Create a set of ints, and put random numbers between 0 and list's length minus one into it in a loop, while the size of the set is not equal the desired number of random elements. Go through the set, and pick list elements as indicated by the numbers in the set. This way would keep your original list intact.

like image 35
Sergey Kalinichenko Avatar answered Oct 24 '22 07:10

Sergey Kalinichenko