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)?
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With