Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove first element satisfying condition in java list

Tags:

java

list

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.

like image 855
Natan Ytzhaki Avatar asked Jan 23 '26 15:01

Natan Ytzhaki


1 Answers

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;
    }
}
like image 91
Kayaman Avatar answered Jan 26 '26 18:01

Kayaman