Is there a PriorityQueue implementation with fixed capacity and custom comparator?

后端 未结 9 2493
后悔当初
后悔当初 2020-11-28 05:59

Related questions:

  • Java PriorityQueue with fixed size
  • How do I use a PriorityQueue?
  • get indexes of n smallest elements in an array
9条回答
  •  萌比男神i
    2020-11-28 06:44

    Create a PriorityQueue that has size limit. It stores N max numbers.

    import java.util.*;
    
    class Demo
    {
        public static > PriorityQueue getPq(final int n, Comparator comparator)
        {
            return new PriorityQueue(comparator)
            {
                boolean full()
                {
                    return size() >= n;
                }
    
                @Override 
                public boolean add(E e)
                {
                    if (!full())
                    {
                        return super.add(e);
                    }
                    else if (peek().compareTo(e) < 0)
                    {
                        poll();
                        return super.add(e);
                    }
                    return false;
                }
    
                @Override
                public boolean offer(E e)
                {
                    if (!full())
                    {
                        return super.offer(e);
                    }
                    else if (peek().compareTo(e) < 0)
                    {
                        poll();
                        return super.offer(e);
                    }
                    return false;
                }
            };
        }
    
        public static void printq(PriorityQueue pq)
        {
            Object o = null;
            while ((o = pq.poll()) != null)
            {
                System.out.println(o);
            }
        }
    
        public static void main (String[] args)
        {
            PriorityQueue pq = getPq(2, new Comparator(){
            @Override
            public int compare(Integer i1, Integer i2)
            {
                return i1.compareTo(i2);
            }
            });
            pq.add(4);
            pq.add(1);
            pq.add(5);
            pq.add(2);
            printq(pq);
        }
    }
    

提交回复
热议问题