欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

从10000000个元素里面找出最大的前100个

程序员文章站 2022-06-07 13:06:47
...

           如题,从最大的10000000个元素里面找出最大的前100个,下面是我的代码实现:

         

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.logging.Logger;


public class FixSizedPriorityQueue<E extends Comparable> {
	private final static Logger logger = Logger.getLogger(FixSizedPriorityQueue.class.getName());
	
	private PriorityQueue<E> queue;
	private int maxSize; // 堆的最大容量

	public FixSizedPriorityQueue(int maxSize) {
		if (maxSize <= 0)
			throw new IllegalArgumentException();
		this.maxSize = maxSize;
		this.queue = new PriorityQueue(maxSize, new Comparator<E>() {
			@Override
			public int compare(E o1, E o2) {
				return o1.compareTo(o2);
			}
		});
	}

	public void add(E e) {
		if (queue.size() < maxSize) { 
			queue.add(e);
		} else { 
			E peek = queue.peek();
			if (e.compareTo(peek) > 0) {
				queue.poll();
				queue.add(e);
			}
		}
	}
	
	public PriorityQueue<E> getQueue(){
		return queue;
	}

	
	public static void main(String[] args) {
		final int length = 10000000;
		final int maxSize = 100;
		
		FixSizedPriorityQueue<Integer> fixedQueue = new FixSizedPriorityQueue<Integer>(maxSize);
		Random random = new Random();
		for(int i =1; i < length; i++){
			fixedQueue.add(random.nextInt(i));
		}
		
		PriorityQueue<Integer> queue = fixedQueue.getQueue();
		Object obj = queue.poll();
		while(obj != null){
			logger.info(obj.toString());
			obj = queue.poll();
		}
	}
}