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)?
Use
to randomize the list, then remove teams one at a time from the list via
teamList.remove(0);
For example:
util class
using
it will random 3 items in your list except item 0 and item 1
Here is a way of doing it using Java streams, without having to create a copy of the original list or shuffling it:
Note: It can become inefficient when
n
is too close to the list size for huge lists.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.
The
shuffle
approach is the most idiomatic: after that, first K elements are exactly what you need.If K is much less than the length of the list, you may want to be faster. In this case, iterate through the list, randomly exchanging the current element with itself or any of the elements after it. After the K-th element, stop and return the K-prefix: it will be already perfectly shuffled, and you don't need to care about the rest of the list.
(obviously, you'd like to use
ArrayList
here)All good ideas but shuffling is expensive. The more efficient method (IMO) would be doing a count controlled loop and picking a random int between 0 and n; where n initially is equal to the length of your list.
In each iteration of the loop you swap the selected item with the item at n-1 on the list and decrement n by one. This way you avoid picking the same element two times and don't have to keep a separate list of selected items.