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 the first element returned by the set's iterator:
Set<Foo> mySet = new LinkedHashSet<Foo>(); // do stuff... if (mySet.size() >= MAX_SET_SIZE) { Iterator<Foo> iter = mySet.iterator(); iter.next(); iter.remove(); }
This is ugly: 3 lines to do something I could do with 1 line if I was using a SortedSet
(for other reasons, a SortedSet
is not an option here):
if (/*stuff*/) { mySet.remove(mySet.first()); }
So is there a cleaner way of doing this, without:
Set
implementation, orAny solutions leveraging Guava are fine.
I am fully aware that sets do not have inherent ordering. I'm asking about removing the first entry as defined by iteration order.
set::erase() erase() function is used to remove elements from a container from the specified position or range.
Set remove() method in Java with Examplesutil. Set. remove(Object O) method is used to remove a particular element from a Set. Parameters: The parameter O is of the type of element maintained by this Set and specifies the element to be removed from the Set.
Java 8 introduced the Set#removeIf() method that uses Iterator#remove() behind the scenes and removes all elements from the set that satisfies the given condition. That's all about removing elements from a Set in Java.
HashSet clear() Method in Java HashSet. clear() method is used to remove all the elements from a HashSet. Using the clear() method only clears all the element from the set and not deletes the set. In other words, we can say that the clear() method is used to only empty an existing HashSet.
LinkedHashSet is a wrapper for LinkedHashMap which supports a simple "remove oldest" policy. To use it as a Set you can do
Set<String> set = Collections.newSetFromMap(new LinkedHashMap<String, Boolean>(){ protected boolean removeEldestEntry(Map.Entry<String, Boolean> eldest) { return size() > MAX_ENTRIES; } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With