How can I take n random elements from an ArrayList
? Ideally, I\'d like to be able to make successive calls to the take()
method to get an
Keep selecting a random element and make sure you do not choose the same element again:
public static List selectRandomElements(List list, int amount)
{
// Avoid a deadlock
if (amount >= list.size())
{
return list;
}
List selected = new ArrayList<>();
Random random = new Random();
int listSize = list.size();
// Get a random item until we got the requested amount
while (selected.size() < amount)
{
int randomIndex = random.nextInt(listSize);
E element = list.get(randomIndex);
if (!selected.contains(element))
{
selected.add(element);
}
}
return selected;
}
In theory this could run endlessly but in practise it is fine. The closer you get the whole original list the slower the runtime of this gets obviously but that is not the point of selecting a random sublist, is it?