Advertisement
mr_magoo

Untitled

Dec 25th, 2013
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.98 KB | None | 0 0
  1. package misc.TopK;
  2.  
  3. import java.util.*;
  4.  
  5. public class TopK {
  6.     int capacity;
  7.     PriorityQueue<Integer> storage;
  8.     public TopK(int capacity){
  9.         this.capacity = capacity;
  10.         storage = new PriorityQueue<>();
  11.     }
  12.  
  13.     public void add(int value){
  14.  
  15.         if (storage.size() >= capacity){
  16.             storage.remove();
  17.         }
  18.         storage.add(value);
  19.     }
  20.  
  21.     public Iterator<Integer> values(){
  22.         return storage.iterator();
  23.     }
  24.  
  25.     public String toString(){
  26.         return storage.toString();
  27.     }
  28.  
  29.     public static void main(String[] args){
  30.  
  31.         Random r = new Random(0);
  32.         ArrayList<Integer> stream = new ArrayList<>();
  33.         for (int i=0; i<15; i++){
  34.             stream.add(r.nextInt(1000));
  35.         }
  36.  
  37.         TopK top = new TopK(5);
  38.         for (int i: stream){
  39.             top.add(i);
  40.         }
  41.         Collections.sort(stream);
  42.         System.out.println(stream);
  43.         System.out.println(top);
  44.  
  45.  
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement