Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package misc.TopK;
- import java.util.*;
- public class TopK {
- int capacity;
- PriorityQueue<Integer> storage;
- public TopK(int capacity){
- this.capacity = capacity;
- storage = new PriorityQueue<>();
- }
- public void add(int value){
- if (storage.size() >= capacity){
- storage.remove();
- }
- storage.add(value);
- }
- public Iterator<Integer> values(){
- return storage.iterator();
- }
- public String toString(){
- return storage.toString();
- }
- public static void main(String[] args){
- Random r = new Random(0);
- ArrayList<Integer> stream = new ArrayList<>();
- for (int i=0; i<15; i++){
- stream.add(r.nextInt(1000));
- }
- TopK top = new TopK(5);
- for (int i: stream){
- top.add(i);
- }
- Collections.sort(stream);
- System.out.println(stream);
- System.out.println(top);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement