Removing the “first” object from a Set

前端 未结 6 1869
北恋
北恋 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

    if (!mySet.isEmpty())
      mySet.remove(mySet.iterator.next());
    

    seems to be less than 3 lines.

    You have to synchronize around it of course if your set is shared by multiple threads.

提交回复
热议问题