Java – removes the “first” object from the collection
•
Java
In some cases, I need to expel the earliest elements in the Java collection The collection is implemented using linkedhashset, which makes it simple: just get rid of the first element returned by the collection 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 do something I can do 1 line if I use sortedset (sortedset is not an option for other reasons)
if (/*stuff*/) { mySet.remove(mySet.first()); }
So is there a cleaner way?
>Change the implementation of set, or write a static practical method?
Any solution using guava is OK
I know perfectly well that sets have no inherent order I asked to delete the first entry defined by the iteration order
Solution
Linkedhashset is the wrapper of LinkedHashMap. It supports a simple "delete oldest" policy 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; } });
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码