James Raitsev
James Raitsev

Reputation: 96391

Getting last of LinkedHashSet

I'd like to store a list of numbers 1,2,3,4 - (lets start with List<Integer>)

I'd like to make sure numbers are unique (ok, fine, Set<Integer>)

I'd like to guarantee order (ok ... LinkedHashSet<Integer>)

I'd like to get the last element from the list ..

What would be the simplest way to get the last number inserted into the LinkedHashSet<Integer> please?

Upvotes: 32

Views: 23345

Answers (6)

ZhekaKozlov
ZhekaKozlov

Reputation: 39536

Since Java 21 LinkedHashSet has getLast() method:

jshell> var set = new LinkedHashSet<>(List.of(1,2,3,4,5));
set ==> [1, 2, 3, 4, 5]

jshell> set.getLast();
$2 ==> 5

Upvotes: 5

corsiKa
corsiKa

Reputation: 82559

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.

Upvotes: 16

user2179737
user2179737

Reputation: 551

here is a implementation that adds method to access the last entry O(1):

LinkedHashSetEx.java

enjoy...

Upvotes: -2

Alexis C.
Alexis C.

Reputation: 93842

With , 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();

Upvotes: 8

Juvanis
Juvanis

Reputation: 25950

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.

Upvotes: 5

Renjith
Renjith

Reputation: 3274

Sets are independent of order.We cannot access element by index.If you require last element,

1)create new ArrayList(Set)

The last element of an arrayList can be accessed easily

Upvotes: -5

Related Questions