Joey Eremondi
Joey Eremondi

Reputation: 8423

Java data structure with push/pop and no duplicates?

I'm looking for a queue-type data structure in Java (preferably in the standard libs) which has the following properties:

Preserving the order of insertion/deletion isn't terribly important.

Set structures have the no duplicates, but don't have the pop operation, and Queue structures don't guarantee no duplicates. Does something fitting my needs exist?

In the interests of avoiding the XY problem, I'm doing a worklist algorithm: nodes that need updating are added to the set, so I want to easily pop the next node that needs updating, and add nodes that need updating without getting a bunch of duplicates if they're already in the worklist.

Upvotes: 1

Views: 682

Answers (2)

shmosel
shmosel

Reputation: 50716

You can use a set's iterator to remove a single element. The ordering will depend on the set implementation.

static <T> T remove(Set<T> set) {
    Iterator<T> iter = set.iterator();
    T element = iter.next();
    iter.remove();
    return element;
}

Upvotes: 2

Louis Wasserman
Louis Wasserman

Reputation: 198014

Use LinkedHashSet, and implement pop as

Iterator<E> iterator = set.iterator();
E result = iterator.next();
iterator.remove();

Upvotes: 5

Related Questions