Making a Java PriorityQueue into a stable priority queue

前端 未结 3 1202
鱼传尺愫
鱼传尺愫 2020-12-11 06:58

I\'m trying to implement a stable (first in first out) priority queue in Java. Supposing that the key is a name and the value is an age, I know I can make an unstable prior

3条回答
  •  长情又很酷
    2020-12-11 07:53

    Very simple implementation based on multiple lists and TreeMap I've done today to solve some task:

    import javax.annotation.Nonnull;
    import java.util.*;
    import java.util.Map.Entry;
    import java.util.function.Function;
    
    public class PriorityFifo {
    
         protected TreeMap> storage = new TreeMap<>();
    
         public void push(E element, int priority) {
            storage.computeIfAbsent(priority, it -> new LinkedList<>()).addLast(element);
         }
    
         public Optional poll() {
            return doWithNextElement(LinkedList::pollFirst);
         }
    
         public Optional peek() {
            return doWithNextElement(LinkedList::getFirst);
         }
    
         protected Optional doWithNextElement(@Nonnull Function, E> f) {
             Entry> entry = storage.firstEntry();
             if (entry==null)
                 return Optional.empty();
             LinkedList list = entry.getValue();
             E element = f.apply(list);
             if (list.isEmpty())
                 storage.remove(entry.getKey());
             return Optional.of(Objects.requireNonNull(element));
    
         }
    
    }
    

    No comparator used for elements, but used internally by TreeMap for queues. My case is that I have only a few of priorities, but a lot of elements, so it should go faster than something using element comparison.

提交回复
热议问题