Reputation: 691
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
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