Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing the "first" object from a Set

Tags:

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:

  • changing the Set implementation, or
  • writing a static utility method?

Any 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.

like image 935
Matt Ball Avatar asked Apr 26 '11 15:04

Matt Ball


People also ask

How do you remove the first element of a set?

set::erase() erase() function is used to remove elements from a container from the specified position or range.

How do I remove one element from a set in Java?

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.

How do I remove an element from a set in Java 8?

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.

How do you remove all elements from a set?

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.


1 Answers

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;     } }); 
like image 107
Peter Lawrey Avatar answered Sep 23 '22 07:09

Peter Lawrey