machinery
machinery

Reputation: 6290

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?

Upvotes: 0

Views: 64

Answers (1)

Marcos Vasconcelos
Marcos Vasconcelos

Reputation: 18276

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;
}

Upvotes: 3

Related Questions