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
I think the way you're doing it is fine. Is this something you do often enough to be worth finding a shorter way? You could do basically the same thing with Guava like this:
Iterables.removeIf(Iterables.limit(mySet, 1), Predicates.alwaysTrue());
That adds the small overhead of wrapping the set and its iterator for limiting and then calling the alwaysTrue()
predicate once... doesn't seem especially worth it to me though.
Edit: To put what I said in a comment in an answer, you could create a SetMultimap
that automatically restricts the number of values it can have per key like this:
SetMultimap multimap = Multimaps.newSetMultimap(map,
new Supplier>() {
public Set get() {
return Sets.newSetFromMap(new LinkedHashMap() {
@Override protected boolean removeEldestEntry(Entry eldestEntry) {
return size() > MAX_SIZE;
}
});
}
});