Top K 问题

public class Application {
    public static void main(String[] args) throws Exception{
        List list = new ArrayList<>();
        Random r = new Random();
        int max = Integer.MIN_VALUE;
        for(int i=0;i<1000;i++){
            int value = r.nextInt(10000);
            max = Math.max(max,value);
            list.add(value);
        }
        PriorityQueue queue = new PriorityQueue<>(10);
        for(int v : list){
            queue.offer(v);
            if(queue.size() > 10){
                queue.poll();
            }
        }
        System.out.println("max = "+max);
        while (!queue.isEmpty()){
            System.out.println(queue.poll());
        }
    }
}

你可能感兴趣的:(Top K 问题)