Removing the “first” object from a Set

前端 未结 6 1868
北恋
北恋 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:19

    I think the way you're doing it is fine. Is this something you do often enough to be worth finding a shorter way? You could do basically the same thing with Guava like this:

    Iterables.removeIf(Iterables.limit(mySet, 1), Predicates.alwaysTrue());
    

    That adds the small overhead of wrapping the set and its iterator for limiting and then calling the alwaysTrue() predicate once... doesn't seem especially worth it to me though.

    Edit: To put what I said in a comment in an answer, you could create a SetMultimap that automatically restricts the number of values it can have per key like this:

    SetMultimap multimap = Multimaps.newSetMultimap(map,
        new Supplier>() {
          public Set get() {
            return Sets.newSetFromMap(new LinkedHashMap() {
              @Override protected boolean removeEldestEntry(Entry eldestEntry) {
                return size() > MAX_SIZE;
              }
            });
          }
        });
    

提交回复
热议问题