Removing the “first” object from a Set

前端 未结 6 1880
北恋
北恋 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 07:16

    LinkedHashSet is a wrapper for LinkedHashMap which supports a simple "remove oldest" policy. To use it as a Set you can do

    Set set = Collections.newSetFromMap(new LinkedHashMap(){
        protected boolean removeEldestEntry(Map.Entry eldest) {
            return size() > MAX_ENTRIES;
        }
    });
    

提交回复
热议问题