Getting last of LinkedHashSet

There’s no prebaked option for this. There’s two off-the-cuff options, and neither are good:

The Order n approach:

public <E> E getLast(Collection<E> c) {
    E last = null;
    for(E e : c) last = e;
    return last;
}

Yuck! But there’s also an Order 1 approach:

class CachedLinkedHashSet<E> extends LinkedHashSet<E> {
    private E last = null;

    @Override
    public boolean add(E e) {
        last = e;
        return super.add(e);
    }
    public E getLast() {
        return last;
    }

}

This is off the cuff, so there might be a subtle bug in it, and for sure this isn’t thread safe or anything. Your needs may vary and lead you to one approach over another.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)