Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - sorted stack

I need a sorted stack. I mean, the element removed from the stack must be the one with great priority. Stack dimension varies a lot (becomes bigger very fast). I need also to search elements in that stack.

Does Java give some good implementation for this? What class or algorithm do you suggest for this?

I'm using a PriorityQueue right now which I consider reasonable except for searching, so I'm wondering if I can use something better.

I also need to remove elements!

In summary: I need to maintain a sorted stack/queue, get the element with greater priority fast and also remove elements as fast as possible

like image 613
msr Avatar asked Dec 04 '25 21:12

msr


1 Answers

TreeSet is a sorted set. Set means no duplicates though. add() adds an item, which is inserted in the correct sorted place. pollLast() removes and returns the last item, pollFirst() removes and returns the first item.

like image 166
Mike Avatar answered Dec 07 '25 11:12

Mike