I have an interesting problem I would like some help with. I have implemented a couple of queues for two separate conditions, one based on FIFO and the other natural order of a key (ConcurrentMap). That is you can image both queues have the same data just ordered differently. The question I have (and I am looking for an efficient way of doing this) if I find the key in the ConcurrentMap based on some criteria, what is the best way of finding the “position” of the key in the FIFO map. Essentially I would like to know whether it is the firstkey (which is easy), or say it is the 10th key.
Any help would be greatly appreciated.
I believe something like the code below will do the job. I’ve left the implementation of element –> key as an abstract method. Note the counter being used to assign increasing numbers to elements. Also note that if
add(...)is being called by multiple threads, the elements in the FIFO are only loosely ordered. That forces the fancymax(...)andmin(...)logic. Its also why the position is approximate. First and last are special cases. First can be indicated clearly. Last is tricky because the current implementation returns a real index.Since this is an approximate location, I would suggest you consider making the API return a
floatbetween0.0and1.0to indicate relative position in the queue.If your code needs to support removal using some means other than
pop(...), you will need to use approximate size, and change the return to((id - min) / (max - min)) * size, with all the appropriateint/floatcasting & rounding.