Getting last of LinkedHashSet

With java-8, you could get a sequential Stream of the LinkedHashSet, skip the first n-1 elements and get the last one.

Integer lastInteger = set.stream().skip(s.size()-1).findFirst().get();

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.


First of all, I agree with corsiKa's solution which suggests an extended version of LinkedHashSet class that contains a pointer to the last element. However, you can use a traditional way by consuming some space for an array:

set.toArray()[ set.size()-1 ] // returns the last element.

Tags:

Java