Take n random elements from a List?

后端 未结 12 1556
天涯浪人
天涯浪人 2020-11-27 16:09

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

12条回答
  •  执念已碎
    2020-11-27 16:18

    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?

提交回复
热议问题