Given a list of elements, I want to get the element with a given property and remove it from the list. The best solution I found is:
Produce
Consider using vanilla java iterators to perform the task:
public static T findAndRemoveFirst(Iterable extends T> collection, Predicate super T> test) {
T value = null;
for (Iterator extends T> it = collection.iterator(); it.hasNext();)
if (test.test(value = it.next())) {
it.remove();
return value;
}
return null;
}
Advantages:
Iterable even without stream() support (at least those implementing remove() on their iterator).Disadvantages:
As for the
Is it possible to combine get and remove in a lambda expression?
other answers clearly show that it is possible, but you should be aware of
ConcurrentModificationException may be thrown when removing element from the list being iterated