Removing the “first” object from a Set

前端 未结 6 1872
北恋
北恋 2021-02-05 06:42

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

6条回答
  •  梦如初夏
    2021-02-05 06:57

    With guava:

    if (!set.isEmpty() && set.size() >= MAX_SET_SIZE) {
        set.remove(Iterables.get(set, 0));
    }
    

    I will also suggest an alternative approach. Yes, it it changing the implementation, but not drastically: extend LinkedHashSet and have that condition in the add method:

    public LimitedLinkedHashSet extends LinkedHashSet {
        public void add(E element) {
             super.add(element);
             // your 5-line logic from above or my solution with guava
        }
    }
    

    It's still 5 line, but it is invisible to the code that's using it. And since this is actually a specific behaviour of the set, it is logical to have it within the set.

提交回复
热议问题