Java combining ArrayList contains() and ArrayList remove()

Viewed 80

Given a matrix of ArrayList<Integer>, I often write in my code

int val = 2;
for(int i = 0 ; i < N ;i++){
    if(matrix[i][0].list.contains(val))
         matrix[i][0].remove(val);
}

Since both .contains() and .remove() run in O(n) time, it got me wondering if there exists a way of combining these two statements and perhaps, thereby increasing run time efficiency somehow? I have done sufficient research on this over a few days span, I was not able to find a convincing answer.

1 Answers

You don't need to do the contains check here at all. Removing an element that doesn't exist doesn't cause any issues.

If you need to do something depending on whether it did contain the element (breaking the loop for example), then you can use the return of List.remove(Object) which returns true if the element was present.

For example:

int val = 2;
for(int i = 0; i < N; i++) {

    if(matrix[i][0].remove(val)) break;
}
Related