I have a list of objects and I want to remove the first of them satisfying some condition, something like:
mylist.removeFirstIf(some condition on object);
Thanks in advance for any help.
Stream the list for a match, then feed the match to the list's remove() method which will remove the first occurrence.
list.stream()
.filter(e -> e.getId().equals("FOO")) // Condition here
.findFirst()
.ifPresent(list::remove);
That's the "look at me, I know streams" version. For the most efficient uselessly micro-optimized version you would use Iterator.
Iterator<Foo> itr = list.iterator();
while(itr.hasNext()) {
if(itr.next().getId().equals("FOO")) {
itr.remove();
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With