rshah
rshah

Reputation: 691

Get n random elements from ArrayList based on condition, and remove them from original list

Take a list: List<MyObject> objects = new ArrayList<>();, where each MyObject has a field String myString;.

How can I "pop" (retrieve and remove) n random elements from the list where myString == "myString"?

Edit:

I have successfully been able to remove a random element from the list, which I can iterate n times, but this seems fairly inefficient. Also there is no comparative aspect in the code I have.

List<MyObject> objects = new ArrayList<>();
MyObject object = objects.get(Math.random() * objects.size());
objects.remove(object);

Upvotes: 1

Views: 95

Answers (1)

Egor
Egor

Reputation: 1409

 List<MyObject> filtered = objects.stream()
            .filter(o -> o.getMyString().equals("myString"))
            .collect(Collectors.toList());

Collections.shuffle(filtered);
List randomList = filtered.subList(0, n);
objects.removeAll(randomList);

Upvotes: 2

Related Questions