Solution
Use the List#remove
method. That is exactly what it was made for, from the documentation:
Removes the first occurrence of the specified element from this list, if it is present (optional operation). If this list does not contain the element, it is unchanged. [...]
boolean wasRemoved = list.remove(data);
Removing ints
However, you might have a minor issue here. Your data type is Integer
and data
is probably of type int
. And there is already a method with the signature List#remove(int)
(documentation) which will remove the element at the given index, not the element itself.
You can bypass this by explicitly boxing your data
to an Integer
, which is what you actually have stored in the list:
boolean wasRemoved = list.remove((Integer) data);
Or directly make the data
variable of type Integer
instead of int
.