Under certain situations, I need to evict the oldest element in a Java Set
. The set is implemented using a LinkedHashSet, which makes this simple: just get rid of t
If you really need to do this at several places in your code, just write a static method.
The other solutions proposed are often slower since they imply calling the Set.remove(Object)
method instead of the Iterator.remove()
method.
@Nullable
public static T removeFirst(Collection extends T> c) {
Iterator extends T> it = c.iterator();
if (!it.hasNext()) { return null; }
T removed = it.next();
it.remove();
return removed;
}