fedor.belov
fedor.belov

Reputation: 23323

What structure is the best for "Get first X elements with best priority"?

I have a lot of elements with int priority. Priority of the element is changable.

Count of operations getFirstPriorityElements(int count) - n
Count of operations updatePriorityOfElement(Object o, int priority) - n

What is best performance structure should I use to get first X elements with best priority?

Upvotes: 0

Views: 279

Answers (1)

Bozho
Bozho

Reputation: 597134

A PriorityQueue or a TreeSet would suit you if you wanted to have a constant priority (the queue is if you want to pop elements, the set - if you want to keep them).

However, with changing priority, you have to reorder the collection on each change. Or better - before each iteration. That should be synchronous, though.

So, make a collection that uses a custom Comparator, and on each invocation of iterator() reorderes its elements. For example you can extend TreeSet and override the iterator() method. Then you call next() n times.

Upvotes: 1

Related Questions