Take n random elements from a List?

后端 未结 12 1572
天涯浪人
天涯浪人 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:21

    The following class retrieve N items from a list of any type. If you provide a seed then on each run it will return the same list, otherwise, the items of the new list will change on each run. You can check its behaviour my running the main methods.

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;
    import java.util.Random;
    
    public class NRandomItem {
        private final List initialList;
    
        public NRandomItem(List list) {
            this.initialList = list;
        }
    
        /**
         * Do not provide seed, if you want different items on each run.
         * 
         * @param numberOfItem
         * @return
         */
        public List retrieve(int numberOfItem) {
            int seed = new Random().nextInt();
            return retrieve(seed, numberOfItem);
        }
    
        /**
         * The same seed will always return the same random list.
         * 
         * @param seed,
         *            the seed of random item generator.
         * @param numberOfItem,
         *            the number of items to be retrieved from the list
         * @return the list of random items
         */
        public List retrieve(int seed, int numberOfItem) {
            Random rand = new Random(seed);
    
            Collections.shuffle(initialList, rand);
            // Create new list with the number of item size
            List newList = new ArrayList<>();
            for (int i = 0; i < numberOfItem; i++) {
                newList.add(initialList.get(i));
            }
            return newList;
        }
    
        public static void main(String[] args) {
            List l1 = Arrays.asList("Foo", "Bar", "Baz", "Qux");
            int seedValue = 10;
            NRandomItem r1 = new NRandomItem<>(l1);
    
            System.out.println(String.format("%s", r1.retrieve(seedValue, 2)));
        }
    }
    

提交回复
热议问题