简体   繁体   中英

Sampling and removing random elements from a list

I have written a method which randomly samples a part of a list. The code is as follows:

private List<String> selectImages(List<String> images, Random rand, int num) {
    List<String> copy = new LinkedList<String>(images);
    Collections.shuffle(copy,rand);
    return copy.subList(0, num);
}

The method takes as input the original list, the random number generator and the number of items to sample.

Now I would like to remove the selected elements from the original list (called images). How can this be done?

Using removeAll in the old list with the argument being your sub sample.

private List<String> selectImages(List<String> images, Random rand, int num) {
    List<String> copy = new LinkedList<String>(images);
    Collections.shuffle(copy,rand);
    List<String> sample = copy.subList(0, num);
    images.removeAll(sample);
    return sample;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM